Search code examples
pythoncupy

Cupy sparse matrix does not correspond to its Scipy equivalence?


I digged the documentation for cupy sparse matrix.

as in scipy I expect to have something like this:

from scipy.sparse import csr_matrix
A_csr = csr_matrix([[1, 2, 0], [0, 0, 3], [4, 0, 5]])

but in cupy here:

To convert CuPy ndarray to CuPy sparse matrices, pass it to the constructor of each CuPy sparse matrix class.

# from cupy.sparse import csr_matrix as cp_csr_matrix
from cupyx.scipy.sparse import csr_matrix as cp_csr_matrix

cA = cp.array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
cA_csr = cp_csr_matrix(cA)

return :

ValueError: Only bool, float32, float64, complex64 and complex128 are supported

I also found this answer which give the same error.


Solution

  • as stated in the error, you need to convert the datatype to either bool, float32/64, or complex64/128:

    import cupy as cp
    from cupyx.scipy.sparse import csr_matrix as cp_csr_matrix
    
    cA = cp.array([[1, 2, 0], [0, 0, 3], [4, 0, 5]], dtype=cp.float32)
    cA_csr = cp_csr_matrix(cA)
    

    BTW, can you please try cA.astype(cp.float64) on your machine and see if there are errors? Mine will throw an NVRTCError. Weird...