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?
JavaScript
x
9
1
import cupy as cp
2
3
a = cp.random.randint(10, size=(4,5,6,7))
4
5
b = a.get()
6
c = cp.asnumpy(a)
7
8
assert type(b) == type(c) and (b == c).all()
9
Advertisement
Answer
cp.asnumpy
is a wrapper calling ndarray.get
. You can see that in the code of cp.asnumpy
:
JavaScript
1
31
31
1
def asnumpy(a, stream=None, order='C', out=None):
2
"""Returns an array on the host memory from an arbitrary source array.
3
4
Args:
5
a: Arbitrary object that can be converted to :class:`numpy.ndarray`.
6
stream (cupy.cuda.Stream): CUDA stream object. If it is specified, then
7
the device-to-host copy runs asynchronously. Otherwise, the copy is
8
synchronous. Note that if ``a`` is not a :class:`cupy.ndarray`
9
object, then this argument has no effect.
10
order ({'C', 'F', 'A'}): The desired memory layout of the host
11
array. When ``order`` is 'A', it uses 'F' if ``a`` is
12
fortran-contiguous and 'C' otherwise.
13
out (numpy.ndarray): The output array to be written to. It must have
14
compatible shape and dtype with those of ``a``'s.
15
16
Returns:
17
numpy.ndarray: Converted array on the host memory.
18
19
"""
20
if isinstance(a, ndarray):
21
return a.get(stream=stream, order=order, out=out)
22
elif hasattr(a, "__cuda_array_interface__"):
23
return array(a).get(stream=stream, order=order, out=out)
24
else:
25
temp = _numpy.asarray(a, order=order)
26
if out is not None:
27
out[ ] = temp
28
else:
29
out = temp
30
return out
31
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.).