Skip to content

Instantly share code, notes, and snippets.

@leofang
Created October 10, 2020 02:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leofang/cf7b9f3909ed9fcbda955bd7483d8dc3 to your computer and use it in GitHub Desktop.
Save leofang/cf7b9f3909ed9fcbda955bd7483d8dc3 to your computer and use it in GitHub Desktop.
Convert CuPy array to PyCUDA array
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]
@leofang
Copy link
Author

leofang commented Oct 10, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment