pycuda icon indicating copy to clipboard operation
pycuda copied to clipboard

can't create GPUArray with shape stored as an ndarray

Open lebedov opened this issue 10 years ago • 3 comments

Passing a shape stored in an ndarray to the GPUArray constructor raises an exception because of ndarray broadcasting:

In [1]: import numpy, pycuda.autoinit, pycuda.gpuarray

In [2]: pycuda.gpuarray.empty(np.array([1,2]), np.float32)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-6a2209df87f6> in <module>()
----> 1 pycuda.gpuarray.empty(np.array([1,2]), np.float32)

/home/lev/Work/miniconda/envs/DEFAULT/lib/python2.7/site-packages/pycuda-2015.1.3-py2.7-linux-x86_64.egg/pycuda/gpuarray.pyc in __init__(self, shape, dtype, allocator, base, gpudata, strides, order)
    182             elif order == "C":
    183                 strides = _c_contiguous_strides(
--> 184                         dtype.itemsize, shape)
    185             else:
    186                 raise ValueError("invalid order: %s" % order)

/home/lev/Work/miniconda/envs/DEFAULT/lib/python2.7/site-packages/pycuda-2015.1.3-py2.7-linux-x86_64.egg/pycuda/compyte/array.pyc in c_contiguous_strides(itemsize, shape)
     37 
     38 def c_contiguous_strides(itemsize, shape):
---> 39     if shape:
     40         strides = [itemsize]
     41         for s in shape[:0:-1]:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

lebedov avatar Sep 06 '15 14:09 lebedov

It would be possible to work around this by casting the shape input to the constructor to a tuple, but PyCUDA has historically not accepted that, and I am not entirely convinced that now is the right time to start. What is the use case where it is necessary that PyCUDA cast the shape to a tuple were the calling code cannot do so?

inducer avatar Sep 06 '15 17:09 inducer

It is possible to cast the shape to a tuple in the calling code, but I mentioned my observation because the GPUArray behavior seemed noticeably different from numpy's array creation functions (array, empty, etc.) which appear to allow shapes that are ndarrays.

lebedov avatar Sep 06 '15 17:09 lebedov

It's true that numpy's behavior serves as a guideline for what PyCUDA should do. If you throw me a pull request, I'll merge it. :-)

inducer avatar Sep 06 '15 17:09 inducer