spmm.py 759 Bytes
Newer Older
rusty1s's avatar
rusty1s committed
1
2
3
from torch_scatter import scatter_add


rusty1s's avatar
rusty1s committed
4
def spmm(index, value, m, n, matrix):
rusty1s's avatar
docs  
rusty1s committed
5
6
7
8
9
    """Matrix product of sparse matrix with dense matrix.

    Args:
        index (:class:`LongTensor`): The index tensor of sparse matrix.
        value (:class:`Tensor`): The value tensor of sparse matrix.
ekagra-ranjan's avatar
ekagra-ranjan committed
10
11
        m (int): The first dimension of corresponding dense matrix.
        n (int): The second dimension of corresponding dense matrix.
rusty1s's avatar
docs  
rusty1s committed
12
13
14
15
        matrix (:class:`Tensor`): The dense matrix.

    :rtype: :class:`Tensor`
    """
rusty1s's avatar
rusty1s committed
16

rusty1s's avatar
rusty1s committed
17
18
    assert n == matrix.size(0)

rusty1s's avatar
rusty1s committed
19
20
21
22
23
24
25
26
    row, col = index
    matrix = matrix if matrix.dim() > 1 else matrix.unsqueeze(-1)

    out = matrix[col]
    out = out * value.unsqueeze(-1)
    out = scatter_add(out, row, dim=0, dim_size=m)

    return out