Home > Software design >  Difference between cupy.asnumpy() and get()
Difference between cupy.asnumpy() and get()

Time:05-13

Given a CuPy array a, there are two ways to get a numpy array from it: a.get() and cupy.asnumpy(a). Is there any practical difference between them?

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()

CodePudding user response:

cp.asnumpy is a wrapper calling ndarray.get. You can see that in the code of 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

As you can see (both in the documentation and in the code), cp.asnumpy supports more input types than just CuPy arrays. It supports inputs that are CUDA objects with the __cuda_array_interface__ attribute and any objects that can be actually converted to a Numpy array. This includes Numpy arrays themselves and iterables (eg. list, generators, etc.).

  • Related