spmm.py 774 Bytes
Newer Older
rusty1s's avatar
rusty1s committed
1
# import torch
rusty1s's avatar
rusty1s committed
2
3
4
from torch_scatter import scatter_add


rusty1s's avatar
rusty1s committed
5
def spmm(index, value, m, n, matrix):
rusty1s's avatar
docs  
rusty1s committed
6
7
8
9
10
    """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
11
12
        m (int): The first dimension of corresponding dense matrix.
        n (int): The second dimension of corresponding dense matrix.
rusty1s's avatar
docs  
rusty1s committed
13
14
15
16
        matrix (:class:`Tensor`): The dense matrix.

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

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

rusty1s's avatar
rusty1s committed
20
21
22
23
24
25
26
27
    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