Directly use Intel mkl library on Scipy sparse matrix to calculate A dot A.T with less memory
<p>I want to call <a href="https://software.intel.com/en-us/node/468640" rel="nofollow noreferrer">mkl.mkl_scsrmultcsr</a> from python. The goal is to calculate a sparse matrix C in <a href="http://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.sparse.csr_matrix.html" rel="nofollow noreferrer">compressed sparse row</a> format. Sparse matrix C is the matrix product between A and transpose of A, where A is also a sparse matrix in csr format. When calculating C = A dot (A.T) with scipy, scipy seems (?) to allocate new memory for holding transpose of A (A.T), and definitely allocates memory for a new C matrix (This means I can't use an existing C matrix). So, I want to try to use the mkl c function directly to decrease memory usage.</p>

<p><a href="https://stackoverflow.com/questions/17158893/does-scipy-support-multithreading-for-sparse-matrix-multiplication-when-using-mk">Here</a> is an answer that works for another mkl function. In that answer, mkl function was faster by 4 times.</p>

<p>The following version finally works after working on it for 4 days. I want to know if I wasted any memory. Would ctype make any copy of the numpy array? Is that that csr->csc conversion in the test function necessary? The intel c function can calculate (A.T) dot A, or A dot A, but not A dot (A.T).</p>

<p>Thanks again.</p>

<pre><code>from ctypes import *
import scipy.sparse as spsp
import numpy as np
import multiprocessing as mp
# June 2nd 2016 version.

# Load the share library
mkl = cdll.LoadLibrary("libmkl_rt.so")

def get_csr_handle(A,clear=False):
    if clear == True:
        A.indptr[:] = 0
        A.indices[:] = 0
        A.data[:] = 0

    a_pointer   = A.data.ctypes.data_as(POINTER(c_float))
     # Array containing non-zero elements of the matrix A.
     # This corresponds to data array of csr_matrix
     # Its length is equal to #non zero elements in A
     # (Can this be longer than actual #non-zero elements?)
    assert A.data.ctypes.data % 16 == 0 # Check alignment

    ja_pointer  = A.indices.ctypes.data_as(POINTER(c_int))
     # Array of column indices of all non-zero elements of A.
     # This corresponds to the indices array of csr_matrix
    assert A.indices.ctypes.data % 16 == 0 # Check alignment

    ia_pointer  = A.indptr.ctypes.data_as(POINTER(c_int))
     # Array of length m+1.
     # a[ia[i]:ia[i+1]] is the value of nonzero entries of
     # the ith row of A.
     # ja[ia[i]:ia[i+1]] is the column indices of nonzero
     # entries of the ith row of A
     # This corresponds to the indptr array of csr_matrix
    assert A.indptr.ctypes.data % 16 == 0 # Check alignment

    A_data_size    = A.data.size
    A_indices_size = A.indices.size
    A_indptr_size  = A.indptr.size

    return (a_pointer, ja_pointer, ia_pointer, A)

def csr_dot_csr_t(A_handle, C_handle, nz=None):
    # Calculate (A.T).dot(A) and put result into C
    #
    # This uses one-based indexing
    #
    # Both C.data and A.data must be in np.float32 type.
    #
    # Number of nonzero elements in C must be greater than
    #     or equal to the size of C.data
    #
    # size of C.indptr must be greater than or equal to
    #     1 + (num rows of A).
    #
    # C_data    = np.zeros((nz), dtype=np.single)
    # C_indices = np.zeros((nz), dtype=np.int32)
    # C_indptr  = np.zeros((m+1),dtype=np.int32)

    #assert len(c_pointer._obj) &gt;= 1 + A_shape[0]


    (a_pointer, ja_pointer, ia_pointer, A) = A_handle
    (c_pointer, jc_pointer, ic_pointer, C) = C_handle
    #print "CCC",C
    #assert type(C.data[0]) == np.float32
    #assert type(A.data[0]) == np.float32
    #assert C.indptr.size &gt;= A.shape[0] + 1

    #CC = A.dot(A.T)
    #assert C.data.size &gt;= nz
    #assert C.indices.size &gt;= nz

    trans_pointer   = byref(c_char('T'))
    sort_pointer    = byref(c_int(0))

    (m, n)          = A.shape
    sort_pointer        = byref(c_int(0))
    m_pointer           = byref(c_int(m))     # Number of rows of matrix A
    n_pointer           = byref(c_int(n))     # Number of columns of matrix A
    k_pointer           = byref(c_int(n))     # Number of columns of matrix B
                                              # should be n when trans='T'
                          # Otherwise, I guess should be m
    ###
    b_pointer   = a_pointer
    jb_pointer  = ja_pointer
    ib_pointer  = ia_pointer
    ###
    if nz == None:
        nz = n*n #*n # m*m # Number of nonzero elements expected
             # probably can use lower value for sparse
             # matrices.
    nzmax_pointer   = byref(c_int(nz))
     # length of arrays c and jc. (which are data and
     # indices of csr_matrix). So this is the number of
     # nonzero elements of matrix C
     #
     # This parameter is used only if request=0.
     # The routine stops calculation if the number of
     # elements in the result matrix C exceeds the
     # specified value of nzmax.

    info = c_int(-3)
    info_pointer = byref(info)
    request_pointer_list = [byref(c_int(0)), byref(c_int(1)), byref(c_int(2))]
    return_list = []
    for ii in [0]:
        request_pointer = request_pointer_list[ii]
        ret = mkl.mkl_scsrmultcsr(trans_pointer, request_pointer, sort_pointer,
                    m_pointer, n_pointer, k_pointer,
                    a_pointer, ja_pointer, ia_pointer,
                    b_pointer, jb_pointer, ib_pointer,
                    c_pointer, jc_pointer, ic_pointer,
                    nzmax_pointer, info_pointer)
        info_val = info.value
        return_list += [ (ret,info_val) ]
    return return_list


def show_csr_internal(A, indent=4):
    # Print data, indptr, and indices
    # of a scipy csr_matrix A
    name = ['data', 'indptr', 'indices']
    mat  = [A.data, A.indptr, A.indices]
    for i in range(3):
        str_print = ' '*indent+name[i]+':\n%s'%mat[i]
        str_print = str_print.replace('\n', '\n'+' '*indent*2)
        print(str_print)

def fix_for_scipy(C,A):
    n = A.shape[1]
    print "fix n", n
    nz =  C.indptr[n] - 1 # -1 as this is still one based indexing.
    print "fix nz", nz
    data = C.data[:nz]

    C.indptr[:n+1] -= 1
    indptr = C.indptr[:n+1]
    C.indices[:nz] -= 1
    indices = C.indices[:nz]
    return spsp.csr_matrix( (data, indices, indptr), shape=(n,n))

def test():
    AA= [[1,0,0,1],
         [1,0,1,0],
         [0,0,1,0]]
    AA = np.random.choice([0,1], size=(3,750000), replace=True, p=[0.99,0.01])
    A_original = spsp.csr_matrix(AA)
    #A = spsp.csr_matrix(A_original, dtype=np.float32)
    A = A_original.astype(np.float32).tocsc()
    #A_original = A.todense()
    A = spsp.csr_matrix( (A.data, A.indices, A.indptr) )
    print  "A:"
    show_csr_internal(A)
    print A.todense()
    A.indptr  += 1 # convert to 1-based indexing
    A.indices += 1 # convert to 1-based indexing
    A_ptrs = get_csr_handle(A)

    C = spsp.csr_matrix( np.ones((3,3)), dtype=np.float32)
    #C.data = C.data[:16].view()
    #C.indptr = C.indptr
    C_ptrs = get_csr_handle(C, clear=True)

    print "C:"
    show_csr_internal(C)    
    print "=call mkl function=" 
    return_list= csr_dot_csr_t(A_ptrs, C_ptrs)
    print "(ret, info):", return_list
    print "C after calling mkl:"
    show_csr_internal(C)    

    C_fix = fix_for_scipy(C,A)
    print "C_fix for scipy:"
    show_csr_internal(C_fix)
    print C_fix.todense()

    print "Original C after fixing:"
    show_csr_internal(C)

    print "scipy's (A).dot(A.T)"
    scipy_ans = (A_original).dot(A_original.T)
    #scipy_ans = spsp.csr_matrix(scipy_ans)
    show_csr_internal(scipy_ans)
    print scipy_ans.todense()

if __name__ == "__main__":
    test()
</code></pre>

<p>Result:</p>

<pre><code>A:
    data:
        [ 1.  1.  1. ...,  1.  1.  1.]
    indptr:
        [    0     0     0 ..., 22673 22673 22673]
    indices:
        [1 0 2 ..., 2 1 2]
[[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 ..., 
 [ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]
C:
    data:
        [ 0.  0.  0.  0.  0.  0.  0.  0.  0.]
    indptr:
        [0 0 0 0]
    indices:
        [0 0 0 0 0 0 0 0 0]
=call mkl function=
(ret, info): [(2, 0)]
C after calling mkl:
    data:
        [ 7576.    77.    83.    77.  7607.   104.    83.   104.  7490.]
    indptr:
        [ 1  4  7 10]
    indices:
        [1 2 3 1 2 3 1 2 3]
fix n 3
fix nz 9
C_fix for scipy:
    data:
        [ 7576.    77.    83.    77.  7607.   104.    83.   104.  7490.]
    indptr:
        [0 3 6 9]
    indices:
        [0 1 2 0 1 2 0 1 2]
[[ 7576.    77.    83.]
 [   77.  7607.   104.]
 [   83.   104.  7490.]]
Original C after fixing:
    data:
        [ 7576.    77.    83.    77.  7607.   104.    83.   104.  7490.]
    indptr:
        [0 3 6 9]
    indices:
        [0 1 2 0 1 2 0 1 2]
scipy's (A.T).dot(A)
    data:
        [  83   77 7576  104   77 7607   83  104 7490]
    indptr:
        [0 3 6 9]
    indices:
        [2 1 0 2 0 1 0 1 2]
[[7576   77   83]
 [  77 7607  104]
 [  83  104 7490]]
</code></pre>

<p>Things learned:</p>

<ol>
<li>index starts from 1 for matrices A, B, and C.</li>
<li>I mixed up c_indptr and c_indices in the original code. Should be ia
= indptr of scipy csr_matrix. ja = indices of scipy csr_matrix.</li>
<li><p>from the code <a href="https://github.com/srkiranraj/spgemm/blob/master/spmm_mkl.cu" rel="nofollow noreferrer">here</a>. Everything is passed to the mkl_?csrmultcsr as a pointer. <code>mkl_scsrmultcsr(&amp;ta, &amp;r[1], &amp;sort, &amp;m, &amp;m, &amp;m, a, ja, ia,  a, ja, ia, c, jc, ic, &amp;nzmax, &amp;info);</code></p></li>
<li><p>I want a mkl function that can work with zero-based index. The mkl.mkl_scsrmultcsr function can only work with one-based indexing. (Or I can one-based indexing for everything. This means using intel c function instead of scipy/numpy for most linear algebra steps.)</p></li>
</ol>