cupy.asnumpy() 和 get() 之间的区别

Ada*_*ker 5 python numpy cupy

给定一个 CuPy 数组a,有两种方法可以从中获取 numpy 数组:a.get()cupy.asnumpy(a)。它们之间有什么实际区别吗?

import cupy as cp

a = cp.random.randint(10, size=(4,5,6,7))

b = a.get()
c = cp.asnumpy(a)

assert type(b) == type(c) and (b == c).all()
Run Code Online (Sandbox Code Playgroud)

Jér*_*ard 2

cp.asnumpy是一个包装器调用ndarray.get。您可以在以下代码中看到cp.asnumpy

def asnumpy(a, stream=None, order='C', out=None):
    """Returns an array on the host memory from an arbitrary source array.

    Args:
        a: Arbitrary object that can be converted to :class:`numpy.ndarray`.
        stream (cupy.cuda.Stream): CUDA stream object. If it is specified, then
            the device-to-host copy runs asynchronously. Otherwise, the copy is
            synchronous. Note that if ``a`` is not a :class:`cupy.ndarray`
            object, then this argument has no effect.
        order ({'C', 'F', 'A'}): The desired memory layout of the host
            array. When ``order`` is 'A', it uses 'F' if ``a`` is
            fortran-contiguous and 'C' otherwise.
        out (numpy.ndarray): The output array to be written to. It must have
            compatible shape and dtype with those of ``a``'s.

    Returns:
        numpy.ndarray: Converted array on the host memory.

    """
    if isinstance(a, ndarray):
        return a.get(stream=stream, order=order, out=out)
    elif hasattr(a, "__cuda_array_interface__"):
        return array(a).get(stream=stream, order=order, out=out)
    else:
        temp = _numpy.asarray(a, order=order)
        if out is not None:
            out[...] = temp
        else:
            out = temp
        return out
Run Code Online (Sandbox Code Playgroud)

正如您所看到的(在文档和代码中),cp.asnumpy支持更多的输入类型而不仅仅是 CuPy 数组。它支持具有__cuda_array_interface__属性的 CUDA 对象以及任何可以实际转换为 Numpy 数组的对象的输入。这包括 Numpy 数组本身和可迭代对象(例如列表、生成器等)。