Attempting numpy conversion when not needed in cupy

Using python3.8 with cupy-cuda111

creating a cupy array and trying to cast to cp.int_ causes cupy assume an implicit conversion to numpy array

import cupy as cp

def test_function(x):
    y = cp.int_(x * 10)
    return(y)

x = cp.array([0.1, 0.2, 0.3, 0.4, 0.5])
y = test_function(x)

print(y)

This I assumed would multiply the scalar and return ([1, 2, 3, 4, 5], dtype=cp.int_) but instead gives:

TypeError: Implicit conversion to a NumPy array is not allowed. Please use `.get()` to construct a NumPy array explicitly.

Why does this error get generated?

How can I multiply and cast to int_ the cp.array?

Answer

You can do

x = x * 10
y = x.astype(cp.int_)
return y

The problem is cp.int_ is np.int_, so calling that would invoke a host function to operate on a GPU array, which is not allowed.

Leave a Reply

Your email address will not be published. Required fields are marked *