diff --git a/dpctl/tensor/_copy_utils.py b/dpctl/tensor/_copy_utils.py index 748ad3641d..cc40f4cb71 100644 --- a/dpctl/tensor/_copy_utils.py +++ b/dpctl/tensor/_copy_utils.py @@ -125,19 +125,29 @@ 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 - `numpy.ndarray`. + :class:`numpy.ndarray`. Args: - arg: An instance of input `numpy.ndarray` - device: array API specification of device where the output array - 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 + arg (array-like): An instance of 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 + a filter selector string, an instance of + :class:`dpctl.SyclDevice`, an instance of + :class:`dpctl.SyclQueue`, 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. + 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 @@ -154,12 +164,15 @@ def to_numpy(usm_ary): to_numpy(usm_ary) Copies content of :class:`dpctl.tensor.usm_ndarray` instance `usm_ary` - into `numpy.ndarray` instance of the same shape and same data type. + into :class:`numpy.ndarray` instance of the same shape and same data type. Args: - usm_ary: An instance of :class:`dpctl.tensor.usm_ndarray` + usm_ary (usm_ndarray): + Input array Returns: - An instance of `numpy.ndarray` populated with content of `usm_ary`. + :class:`numpy.ndarray`: + An instance of :class:`numpy.ndarray` populated with content of + `usm_ary` """ return _copy_to_numpy(usm_ary) @@ -169,18 +182,24 @@ def asnumpy(usm_ary): asnumpy(usm_ary) Copies content of :class:`dpctl.tensor.usm_ndarray` instance `usm_ary` - into `numpy.ndarray` instance of the same shape and same data type. + into :class:`numpy.ndarray` instance of the same shape and same data + type. Args: - usm_ary: An instance of :class:`dpctl.tensor.usm_ndarray` + usm_ary (usm_ndarray): + Input array Returns: - An instance of `numpy.ndarray` populated with content of `usm_ary`. + :class:`numpy.ndarray`: + An instance of :class:`numpy.ndarray` populated with content + of `usm_ary` """ return _copy_to_numpy(usm_ary) class Dummy: - "Helper class with specified __sycl_usm_array_interface__ attribute" + """ + Helper class with specified ``__sycl_usm_array_interface__`` attribute + """ def __init__(self, iface): self.__sycl_usm_array_interface__ = iface @@ -280,10 +299,20 @@ def _copy_from_usm_ndarray_to_usm_ndarray(dst, src): def copy(usm_ary, order="K"): - """ - Creates a copy of given instance of `usm_ndarray`. + """copy(ary, order="K") + + Creates a copy of given instance of :class:`dpctl.tensor.usm_ndarray`. + + 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. - Memory layour of the copy is controlled by `order` keyword, + Memory layout of the copy is controlled by `order` keyword, following NumPy's conventions. The `order` keywords can be one of the following: @@ -342,10 +371,31 @@ def copy(usm_ary, order="K"): def astype(usm_ary, newdtype, order="K", casting="unsafe", copy=True): - """ - astype(usm_array, new_dtype, order="K", casting="unsafe", copy=True) + """ astype(array, new_dtype, order="K", casting="unsafe", \ + copy=True) + + Returns a copy of the :class:`dpctl.tensor.usm_ndarray`, cast to a + specified type. - Returns a copy of the array, cast to a specified type. + Args: + array (usm_ndarray): + An input array. + new_dtype (dtype): + The data type of the resulting array. + 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. + + Returns: + usm_ndarray: + An array with requested data type. A view can be returned, if possible, when `copy=False` is used. """ diff --git a/dpctl/tensor/_ctors.py b/dpctl/tensor/_ctors.py index f03553622f..cecbdadb58 100644 --- a/dpctl/tensor/_ctors.py +++ b/dpctl/tensor/_ctors.py @@ -277,7 +277,7 @@ def _asarray_from_numpy_ndarray( def _is_object_with_buffer_protocol(obj): - "Returns True if object support Python buffer protocol" + "Returns `True` if object support Python buffer protocol" try: # use context manager to ensure # buffer is instantly released @@ -291,12 +291,14 @@ def _ensure_native_dtype_device_support(dtype, dev) -> None: """Check that dtype is natively supported by device. Arg: - dtype: elemental data-type - dev: :class:`dpctl.SyclDevice` - Return: + 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. + ValueError - if device does not natively support this dtype. """ if dtype in [dpt.float64, dpt.complex128] and not dev.has_aspect_fp64: raise ValueError( @@ -329,11 +331,13 @@ def asarray( Converts `obj` to :class:`dpctl.tensor.usm_ndarray`. Args: - obj: Python object to convert. Can be an instance of `usm_ndarray`, + 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 `numpy.ndarray`, an object supporting Python buffer protocol, - a Python scalar, or a (possibly nested) sequence of Python scalars. + 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`. @@ -349,7 +353,7 @@ def asarray( 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`. + :attr:`dpctl.tensor.usm_array.device`. Default: `None`. usm_type ("device"|"shared"|"host", optional): The type of SYCL USM allocation for the output array. For `usm_type=None` the allocation type is inferred from the input if `obj` has USM allocation, or @@ -361,6 +365,10 @@ def asarray( 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`. + + Returns: + usm_ndarray: + Array created from input object. """ # 1. Check that copy is a valid keyword if copy not in [None, True, False]: @@ -479,8 +487,11 @@ def empty( usm_type="device", sycl_queue=None, ): - """ - Creates `usm_ndarray` from uninitialized USM allocation. + """ empty(shape, dtype=None, order="C", device=None, \ + usm_type="device", sycl_queue=None) + + Creates :class:`dpctl.tensor.usm_ndarray` from uninitialized + USM allocation. Args: shape (tuple): Dimensions of the array to be created. @@ -493,8 +504,8 @@ def empty( 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`. + :class:`dpctl.SyclQueue`, or a `Device` object returned by + :attr:`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"`. sycl_queue (:class:`dpctl.SyclQueue`, optional): The SYCL queue to use @@ -504,6 +515,10 @@ def empty( 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`. + + Returns: + usm_ndarray: + Created empty array. """ if not isinstance(order, str) or len(order) == 0 or order[0] not in "CcFf": raise ValueError( @@ -589,7 +604,7 @@ def arange( 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`. + :attr:`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'`. sycl_queue (:class:`dpctl.SyclQueue`, optional): The SYCL queue to use @@ -599,6 +614,10 @@ def arange( 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`. + + Returns: + usm_ndarray: + Array populated with evenly spaced values. """ if stop is None: stop = start @@ -672,7 +691,8 @@ def zeros( """ 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. + Returns a new :class:`dpctl.tensor.usm_ndarray` having a specified + shape and filled with zeros. Args: shape (tuple): Dimensions of the array to be created. @@ -684,8 +704,8 @@ def zeros( 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`. + :class:`dpctl.SyclQueue`, or a `Device` object returned by + :attr:`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"`. sycl_queue (:class:`dpctl.SyclQueue`, optional): The SYCL queue to use @@ -695,6 +715,10 @@ def zeros( 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`. + + 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( @@ -727,8 +751,8 @@ def ones( """ 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. + Returns a new :class:`dpctl.tensor.usm_ndarray` having a specified + shape and filled with ones. Args: shape (tuple): Dimensions of the array to be created. @@ -740,8 +764,8 @@ def ones( 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`. + :class:`dpctl.SyclQueue`, or a `Device` object returned by + :attr:`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"`. sycl_queue (:class:`dpctl.SyclQueue`, optional): The SYCL queue to use @@ -751,6 +775,10 @@ def ones( 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`. + + 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( @@ -784,8 +812,8 @@ def full( """ 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`. + Returns a new :class:`dpctl.tensor.usm_ndarray` having a specified + shape and filled with `fill_value`. Args: shape (tuple): Dimensions of the array to be created. @@ -798,8 +826,8 @@ def full( 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`. + :class:`dpctl.SyclQueue`, or a `Device` object returned by + :attr:`dpctl.tensor.usm_array.device`. Default: `None`. 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 @@ -812,6 +840,10 @@ def full( 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`. + + 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( @@ -867,8 +899,8 @@ def empty_like( """ 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`. + Returns an uninitialized :class:`dpctl.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 @@ -881,8 +913,8 @@ def empty_like( 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`. + :class:`dpctl.SyclQueue`, or a `Device` object returned by + :attr:`dpctl.tensor.usm_array.device`. Default: `None`. 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`. @@ -893,6 +925,10 @@ def empty_like( 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`. + + 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)}.") @@ -928,7 +964,8 @@ def zeros_like( """ zeros_like(x, dtype=None, order="C", \ device=None, usm_type=None, sycl_queue=None) - Creates `usm_ndarray` from USM allocation initialized with zeros. + Creates :class:`dpctl.tensor.usm_ndarray` from USM allocation + initialized with zeros. Args: x (usm_ndarray): Input array from which to derive the shape of the @@ -942,8 +979,8 @@ def zeros_like( 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`. + :class:`dpctl.SyclQueue`, or a `Device` object returned by + :attr:`dpctl.tensor.usm_array.device`. Default: `None`. 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`. @@ -954,6 +991,10 @@ def zeros_like( 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`. + + 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)}.") @@ -988,8 +1029,8 @@ def ones_like( """ 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`. + Returns a new :class:`dpctl.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 @@ -1002,8 +1043,8 @@ def ones_like( 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`. + :class:`dpctl.SyclQueue`, or a `Device` object returned by + :attr:`dpctl.tensor.usm_array.device`. Default: `None`. 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`. @@ -1014,6 +1055,10 @@ def ones_like( 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`. + + 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)}.") @@ -1054,8 +1099,8 @@ def full_like( """ 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`. + Returns a new :class:`dpctl.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 @@ -1070,8 +1115,8 @@ def full_like( 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`. + :class:`dpctl.SyclQueue`, or a `Device` object returned by + :attr:`dpctl.tensor.usm_array.device`. Default: `None`. 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`. @@ -1083,6 +1128,10 @@ def full_like( 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`. + + 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)}.") @@ -1128,7 +1177,8 @@ def linspace( linspace(start, stop, num, dtype=None, device=None, endpoint=True, \ sycl_queue=None, usm_type="device") - Returns evenly spaced numbers of specified interval. + Returns :class:`dpctl.tensor.usm_ndarray` array populated with + evenly spaced numbers of specified interval. Args: start: the start of the interval. @@ -1149,8 +1199,8 @@ def linspace( 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`. + :class:`dpctl.SyclQueue`, or a `Device` object returned by + :attr:`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"`. sycl_queue (:class:`dpctl.SyclQueue`, optional): The SYCL queue to use @@ -1162,6 +1212,11 @@ def linspace( and copying. Default: `None`. endpoint: boolean indicating whether to include `stop` in the interval. Default: `True`. + + Returns: + usm_ndarray: + Array populated with evenly spaced numbers in the requested + interval. """ sycl_queue = normalize_queue_device(sycl_queue=sycl_queue, device=device) dpctl.utils.validate_usm_type(usm_type, allow_none=False) @@ -1210,7 +1265,8 @@ def eye( 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 :class:`dpctl.tensor.usm_ndarray` with ones on the `k`-th + diagonal. Args: n_rows: number of rows in the output array. @@ -1229,8 +1285,8 @@ def eye( 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`. + :class:`dpctl.SyclQueue`, or a `Device` object returned by + :attr:`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"`. sycl_queue (:class:`dpctl.SyclQueue`, optional): The SYCL queue to use @@ -1240,6 +1296,10 @@ def eye( 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`. + + Returns: + usm_ndarray: + A diagonal matrix. """ if not isinstance(order, str) or len(order) == 0 or order[0] not in "CcFf": raise ValueError( @@ -1290,6 +1350,10 @@ def tril(x, k=0): 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: + usm_ndarray: + A lower-triangular array or a stack of lower-triangular arrays. """ if not isinstance(x, dpt.usm_ndarray): raise TypeError( @@ -1356,6 +1420,10 @@ def triu(x, k=0): 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: + usm_ndarray: + An upper-triangular array or a stack of upper-triangular arrays. """ if not isinstance(x, dpt.usm_ndarray): raise TypeError( @@ -1410,7 +1478,8 @@ def triu(x, k=0): def meshgrid(*arrays, indexing="xy"): """meshgrid(*arrays, indexing="xy") - Creates list of `usm_ndarray` coordinate matrices from vectors. + Creates list of :class:`dpctl.tensor.usm_ndarray` coordinate matrices + from vectors. Args: arrays (usm_ndarray): an arbitrary number of one-dimensional arrays @@ -1422,7 +1491,7 @@ def meshgrid(*arrays, indexing="xy"): keyword has no effect and should be ignored. Default: `xy`. Returns: - out (List[array]): list of `N` arrays, where `N` is the number of + 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`, ... diff --git a/dpctl/tensor/_device.py b/dpctl/tensor/_device.py index af36239f10..63e9cee80f 100644 --- a/dpctl/tensor/_device.py +++ b/dpctl/tensor/_device.py @@ -21,12 +21,12 @@ class Device: """ - Class representing Data-API concept of device. + An object representing Data-API concept of device. This is a wrapper around :class:`dpctl.SyclQueue` with custom formatting. The class does not have public constructor, - but a class method `create_device` to construct it from device= keyword - argument in Array-API functions. + but a class method :meth:`dpctl.tensor.Device.create_device` to construct + it from `device` keyword argument in Array-API functions. Instance can be queried for ``sycl_queue``, ``sycl_context``, or ``sycl_device``. @@ -39,13 +39,13 @@ def __new__(cls, *args, **kwargs): raise TypeError("No public constructor") @classmethod - def create_device(cls, dev=None): - """Device.create_device(dev=None) + def create_device(cls, device=None): + """Device.create_device(device=None) Creates instance of Device from argument. Args: - dev: + device: Device specification, i.e. `None`, :class:`.Device`, :class:`dpctl.SyclQueue`, or a :class:`dpctl.SyclDevice` corresponding to a root SYCL device. @@ -55,6 +55,7 @@ def create_device(cls, dev=None): SyclQueueCreationError: if :class:`dpctl.SyclQueue` could not be created from the argument """ + dev = device obj = super().__new__(cls) if isinstance(dev, Device): obj.sycl_queue_ = dev.sycl_queue @@ -153,11 +154,13 @@ def normalize_queue_device(sycl_queue=None, device=None): :class:`dpctl.tensor.Device`, optional): array-API keyword indicating non-partitioned SYCL device where array is allocated. + Returns :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` is returned. + Raises: TypeError: if argument is not of the expected type, or keywords imply incompatible queues. diff --git a/dpctl/tensor/_dlpack.pyx b/dpctl/tensor/_dlpack.pyx index eb9849c5e8..78d89c055e 100644 --- a/dpctl/tensor/_dlpack.pyx +++ b/dpctl/tensor/_dlpack.pyx @@ -97,7 +97,7 @@ cdef extern from 'dlpack/dlpack.h' nogil: def get_build_dlpack_version(): """ Returns the string value of DLPACK_VERSION from dlpack.h - `dpctl.tensor` was built with. + :module:`dpctl.tensor` was built with. Returns: A string value of the version of DLPack used to build @@ -480,7 +480,7 @@ cpdef from_dlpack(array): protocol. Returns: - out (usm_ndarray): + usm_ndarray: An array with a view into the tensor underlying the input `obj`. Raises: diff --git a/dpctl/tensor/_indexing_functions.py b/dpctl/tensor/_indexing_functions.py index a2301b5fb2..d73a2e7952 100644 --- a/dpctl/tensor/_indexing_functions.py +++ b/dpctl/tensor/_indexing_functions.py @@ -58,7 +58,7 @@ def take(x, indices, /, *, axis=None, mode="wrap"): Default: `"wrap"`. Returns: - out: usm_ndarray + usm_ndarray: Array with shape x.shape[:axis] + indices.shape + x.shape[axis + 1:] filled with elements from x. """ @@ -233,7 +233,7 @@ def extract(condition, arr): Input array of the same size as `condition`. Returns: - out (usm_ndarray): + usm_ndarray: Rank 1 array of values from `arr` where `condition` is True. """ if not isinstance(condition, dpt.usm_ndarray): @@ -335,7 +335,7 @@ def nonzero(arr): arr (usm_ndarray): Input array, which has non-zero array rank. Returns: - out: Tuple[usm_ndarray, ...] + 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 caa36a3dc8..845f2d6f80 100644 --- a/dpctl/tensor/_manipulation_functions.py +++ b/dpctl/tensor/_manipulation_functions.py @@ -33,7 +33,7 @@ class finfo_object(np.finfo): """ - numpy.finfo subclass which returns Python floating-point scalars for + `numpy.finfo` subclass which returns Python floating-point scalars for `eps`, `max`, `min`, and `smallest_normal` attributes. """ @@ -129,7 +129,8 @@ def permute_dims(X, axes): `(0,1,...,N-1)` where `N` is the number of axes (dimensions) of `x`. Returns: - out (usm_narray): an array containing the axes permutation. + usm_narray: + 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`. @@ -174,14 +175,15 @@ def expand_dims(X, axis): 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. + 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 provided axis position is invalid. + IndexError: if `axis` value is invalid. """ if not isinstance(X, dpt.usm_ndarray): raise TypeError(f"Expected usm_ndarray type, got {type(X)}.") @@ -207,7 +209,8 @@ def squeeze(X, axis=None): axis (Union[int, Tuple[int,...]]): axis (or axes) to squeeze. Returns: - out (usm_ndarray): output array is a view, if possible, + 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 @@ -247,7 +250,7 @@ def broadcast_to(X, shape): """broadcast_to(x, shape) Broadcast an array to a new `shape`; returns the broadcasted - array as a view. + :class:`dpctl.tensor.usm_ndarray` as a view. Args: x (usm_ndarray): input array @@ -255,7 +258,8 @@ def broadcast_to(X, shape): compatible with `x` according to broadcasting rules. Returns: - out (usm_ndarray): an array with the specified `shape`. + 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. @@ -282,14 +286,16 @@ def broadcast_to(X, shape): def broadcast_arrays(*args): """broadcast_arrays(*arrays) - Broadcasts one or more usm_ndarrays against one another. + Broadcasts one or more :class:`dpctl.tensor.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 + 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. @@ -322,7 +328,8 @@ def flip(X, axis=None): axes are flipped. Default: `None`. Returns: - out (usm_ndarray): a view of `x` with the entries of `axis` reversed. + 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)}.") @@ -364,7 +371,8 @@ def roll(X, shift, axis=None): Default: `None`. Returns: - out (usm_ndarray): an array having the same `dtype`, `usm_type` and + usm_ndarray: + An array having the same `dtype`, `usm_type` and `device` attributes as `x` and whose elements are shifted relative to `x`. """ @@ -513,7 +521,8 @@ def concat(arrays, axis=0): being counted from the last dimension. Default: `0`. Returns: - out (usm_ndarray): an output array containing the concatenated + usm_ndarray: + An output array containing the concatenated values. The output array data type is determined by Type Promotion Rules of array API. @@ -581,7 +590,8 @@ def stack(arrays, axis=0): Default: `0`. Returns: - out (usm_ndarray): an output array having rank `N+1`, where `N` is + 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. @@ -638,7 +648,8 @@ def can_cast(from_, to, casting="safe"): controls what kind of data casting may occur. Returns: - out (bool): True if cast can occur according to the casting rule. + bool: + Gives `True` if cast can occur according to the casting rule. """ if isinstance(to, dpt.usm_ndarray): raise TypeError("Expected dtype type.") @@ -662,10 +673,12 @@ def result_type(*arrays_and_dtypes): the arguments. Args: - arrays_and_dtypes: An arbitrary length sequence of arrays or dtypes. + arrays_and_dtypes (object): + An arbitrary length sequence of arrays or dtypes. Returns: - out (dtype): the dtype resulting from an operation involving the + dtype: + The dtype resulting from an operation involving the input arrays and dtypes. """ dtypes = [ @@ -684,11 +697,13 @@ def iinfo(dtype): Returns machine limits for integer data types. Args: - dtype (dtype, usm_ndarray): integer dtype or + dtype (dtype, usm_ndarray): + integer dtype or an array with integer dtype. Returns: - out (iinfo_object): an object with the followign attributes + iinfo_object: + An object with the followign attributes * bits: int number of bits occupied by the data type * max: int @@ -716,7 +731,7 @@ def finfo(dtype): data type. Returns: - out (finfo_object): + finfo_object: an object have the following attributes * bits: int number of bits occupied by dtype. @@ -755,7 +770,8 @@ def unstack(X, axis=0): Default: `0`. Returns: - Tuple[usm_ndarray,...]: A tuple of arrays. + Tuple[usm_ndarray,...]: + Output sequence of arrays which are views into the input array. Raises: AxisError: if the `axis` value is invalid. @@ -790,7 +806,8 @@ def moveaxis(X, src, dst): in the half-open interval `[-N, N)`. Returns: - usm_narray: Array with moved axes. + usm_narray: + 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`. @@ -834,7 +851,8 @@ def swapaxes(X, axis1, axis2): a valid `axis` must be in the half-open interval `[-N, N)`. Returns: - usm_narray: Array with swapped axes. + usm_narray: + 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`. diff --git a/dpctl/tensor/_print.py b/dpctl/tensor/_print.py index c92172286e..ce6923597e 100644 --- a/dpctl/tensor/_print.py +++ b/dpctl/tensor/_print.py @@ -110,7 +110,7 @@ def set_print_options( precision=None, floatmode=None, suppress=None, nanstr=None, infstr=None, sign=None, numpy=False) - Set options for printing ``dpctl.tensor.usm_ndarray`` class. + Set options for printing :class:`dpctl.tensor.usm_ndarray` class. Args: linewidth (int, optional): Number of characters printed per line. @@ -184,10 +184,10 @@ def get_print_options(): """get_print_options() Returns a copy of current options for printing - ``dpctl.tensor.usm_ndarray`` class. + :class:`dpctl.tensor.usm_ndarray` class. Returns: - out (dict): dictionary with array + dict: dictionary with array printing option settings. Options: @@ -262,7 +262,7 @@ def usm_ndarray_str( suffix="") Returns a string representing the elements of a - ``dpctl.tensor.usm_ndarray``. + :class:`dpctl.tensor.usm_ndarray`. Args: x (usm_ndarray): Input array. @@ -322,7 +322,7 @@ def usm_ndarray_str( Default: "" Returns: - out (str): string representation of intpu array. + str: string representation of input array. """ if not isinstance(x, dpt.usm_ndarray): raise TypeError(f"Expected dpctl.tensor.usm_ndarray, got {type(x)}") @@ -365,7 +365,7 @@ def usm_ndarray_repr( suppress=None, prefix="") Returns a formatted string representing the elements - of a ``dpctl.tensor.usm_ndarray`` and its data type, + of a :class:`dpctl.tensor.usm_ndarray` and its data type, if not a default type. Args: @@ -385,7 +385,7 @@ def usm_ndarray_repr( Default: "" Returns: - out (str): formatted string representing the input array + 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)}") diff --git a/dpctl/tensor/_reshape.py b/dpctl/tensor/_reshape.py index 67350c53b6..99726af4d3 100644 --- a/dpctl/tensor/_reshape.py +++ b/dpctl/tensor/_reshape.py @@ -92,7 +92,7 @@ def reshape(X, shape, order="C", copy=None): and `"F"` for F-contiguous, or column-major layout. Returns: - out (usm_ndarray): + usm_ndarray: Reshaped array is a view, if possible, and a copy otherwise with memory layout as indicated by `order` keyword. diff --git a/dpctl/tensor/_usmarray.pyx b/dpctl/tensor/_usmarray.pyx index ea57959cb6..f857b50581 100644 --- a/dpctl/tensor/_usmarray.pyx +++ b/dpctl/tensor/_usmarray.pyx @@ -108,17 +108,74 @@ cdef class usm_ndarray: offset=0, order="C", buffer_ctor_kwargs=dict(), \ array_namespace=None) - See :class:`dpctl.memory.MemoryUSMShared` for allowed - keyword arguments. - - `buffer` can be 'shared', 'host', 'device' to allocate + 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. + 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: ``"|f8"``. + 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 alloctors 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 - the specified `buffer_ctor_kwrds`; `buffer` can be an + the specified ``buffer_ctor_kwrds``; ``buffer`` can be an instance of :class:`dpctl.memory.MemoryUSMShared`, :class:`dpctl.memory.MemoryUSMDevice`, or - :class:`dpctl.memory.MemoryUSMHost`; `buffer` can also be - another usm_ndarray instance, in which case its underlying - MemoryUSM* buffer is used for buffer. + :class:`dpctl.memory.MemoryUSMHost`; ``buffer`` can also be + another :class:`dpctl.tensor.usm_ndarray` instance, in which case its + underlying ``MemoryUSM*`` buffer is used. """ cdef void _reset(usm_ndarray self): @@ -313,7 +370,7 @@ cdef class usm_ndarray: """ Returns pointer to shape C-array for this array. - C-array has at least `ndim` non-negative elements, + C-array has at least ``ndim`` non-negative elements, which determine the range of permissible indices addressing individual elements of this array. """ @@ -324,7 +381,7 @@ cdef class usm_ndarray: Returns pointer to strides C-array for this array. The pointer can be NULL (contiguous array), or the - array size is at least `ndim` elements + array size is at least ``ndim`` elements """ return self.strides_ @@ -373,7 +430,8 @@ cdef class usm_ndarray: @property def __sycl_usm_array_interface__(self): """ - Gives __sycl_usm_array_interface__ dictionary describing the array + Gives ``__sycl_usm_array_interface__`` dictionary describing + the array. """ cdef Py_ssize_t byte_offset = -1 cdef int item_size = -1 @@ -443,7 +501,7 @@ cdef class usm_ndarray: def shape(self, new_shape): """ Setting shape is only allowed when reshaping to the requested - dimensions can be returned as view. Use `dpctl.tensor.reshape` + dimensions can be returned as view. Use :func:`dpctl.tensor.reshape` to reshape the array in all other cases. """ cdef int new_nd = -1 @@ -528,14 +586,15 @@ cdef class usm_ndarray: @property def flags(self): """ - Returns dpctl.tensor._flags object. + Returns :class:`dpctl.tensor._flags` object. """ return _flags.Flags(self, self.flags_) @property def usm_type(self): """ - USM type of underlying memory. Can be 'device', 'shared', or 'host'. + USM type of underlying memory. Can be ``"device"``, ``"shared"``, + or ``"host"``. See: https://docs.oneapi.com/versions/latest/dpcpp/iface/usm.html """ @@ -574,14 +633,14 @@ cdef class usm_ndarray: @property def sycl_queue(self): """ - Returns `dpctl.SyclQueue` object associated with USM data. + Returns :class:`dpctl.SyclQueue` object associated with USM data. """ return self.get_sycl_queue() @property def sycl_device(self): """ - Returns `dpctl.SyclDevice` object on which USM data was allocated. + Returns :class:`dpctl.SyclDevice` object on which USM data was allocated. """ q = self.sycl_queue return q.sycl_device @@ -596,7 +655,7 @@ cdef class usm_ndarray: @property def sycl_context(self): """ - Returns `dpctl.SyclContext` object to which USM data is bound. + Returns :class:`dpctl.SyclContext` object to which USM data is bound. """ q = self.sycl_queue return q.sycl_context @@ -690,7 +749,8 @@ cdef class usm_ndarray: def to_device(self, target): - """ + """ to_device(target_device) + Transfers this array to specified target device. :Example: @@ -710,7 +770,8 @@ cdef class usm_ndarray: print(timer.dt) Args: - target: array API concept of target device. + 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 @@ -718,10 +779,11 @@ cdef class usm_ndarray: object returned by :attr:`dpctl.tensor.usm_array.device`. Returns: - 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. + 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 @@ -869,8 +931,8 @@ cdef class usm_ndarray: def __dlpack_device__(self): """ - Gives a tuple (`device_type`, `device_id`) corresponding to `DLDevice` - entry in `DLTensor` in DLPack protocol. + Gives a tuple (`device_type`, `device_id`) corresponding to ``DLDevice`` + entry in ``DLTensor`` in DLPack protocol. The tuple describes the non-partitioned device where the array has been allocated.