from_dlpack¶
- from_dlpack(x: object, /, *, device: device | None = None, copy: bool | None = None) array¶
Returns a new array containing the data from another (array) object with a
__dlpack__method.- Parameters:
x (object) – input (array) object.
device (Optional[device]) –
device on which to place the created array. If
deviceisNoneandxsupports DLPack, the output array must be on the same device asx. Default:None.The v2023.12 standard only mandates that a compliant library should offer a way for
from_dlpackto return an array whose underlying memory is accessible to the Python interpreter, when the correspondingdeviceis provided. If the array library does not support such cases at all, the function must raiseBufferError. If a copy must be made to enable this support butcopyis set toFalse, the function must raiseValueError.Other device kinds will be considered for standardization in a future version of this API standard.
copy (Optional[bool]) – boolean indicating whether or not to copy the input. If
True, the function must always copy. IfFalse, the function must never copy, and raiseBufferErrorin case a copy is deemed necessary (e.g. if a cross-device data movement is requested, and it is not possible without a copy). IfNone, the function must reuse the existing memory buffer if possible and copy otherwise. Default:None.
- Returns:
out (array) – an array containing the data in
x.Note
The returned array may be either a copy or a view. See Data interchange mechanisms for details.
- Raises:
BufferError – The
__dlpack__and__dlpack_device__methods on the input array may raiseBufferErrorwhen the data cannot be exported as DLPack (e.g., incompatible dtype, strides, or device). It may also raise other errors when export fails for other reasons (e.g., not enough memory available to materialize the data).from_dlpackmust propagate such exceptions.AttributeError – If the
__dlpack__and__dlpack_device__methods are not present on the input array. This may happen for libraries that are never able to export their data with DLPack.ValueError – If data exchange is possible via an explicit copy but
copyis set toFalse.
Notes
See
array.__dlpack__()for implementation suggestions forfrom_dlpackin order to handle DLPack versioning correctly.A way to move data from two array libraries to the same device (assumed supported by both libraries) in a library-agnostic fashion is illustrated below:
def func(x, y): xp_x = x.__array_namespace__() xp_y = y.__array_namespace__() # Other functions than `from_dlpack` only work if both arrays are from the same library. So if # `y` is from a different one than `x`, let's convert `y` into an array of the same type as `x`: if not xp_x == xp_y: y = xp_x.from_dlpack(y, copy=True, device=x.device) # From now on use `xp_x.xxxxx` functions, as both arrays are from the library `xp_x` ...
Changed in version 2023.12: Required exceptions to address unsupported use cases.
Changed in version 2023.12: Added device and copy support.