Created
October 10, 2020 02:59
-
-
Save leofang/cf7b9f3909ed9fcbda955bd7483d8dc3 to your computer and use it in GitHub Desktop.
Convert CuPy array to PyCUDA array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cupy as cp | |
from pycuda import gpuarray | |
import pycuda.autoinit # this import creates a CUDA context! | |
def from_cupy(arr): | |
shape = arr.shape | |
dtype = arr.dtype | |
# a dummy object always returns the underlying pointer address | |
def alloc(x): | |
return arr.data.ptr | |
if arr.flags.c_contiguous: | |
order = 'C' | |
elif arr.flags.f_contiguous: | |
order = 'F' | |
else: | |
raise ValueError('arr order cannot be determined') | |
return gpuarray.GPUArray(shape=shape, | |
dtype=dtype, | |
allocator=alloc, | |
order=order) | |
a = cp.arange(10) | |
x = from_cupy(a) | |
x+=3 | |
print(a) # output: [ 3 4 5 6 7 8 9 10 11 12] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For the record, this is to help a friend transition from PyCUDA to CuPy, which is an advise that I give everywhere as a CuPy core contributor.