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


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

    Args:
        index (:class:`LongTensor`): The index tensor of sparse matrix.
rusty1s's avatar
add doc  
rusty1s committed
11
12
13
        value (:class:`Tensor`): The value tensor of sparse matrix, either of
            floating-point or integer type. Does not work for boolean and
            complex number data types.
wang-ps's avatar
wang-ps committed
14
15
        m (int): The first dimension of sparse matrix.
        n (int): The second dimension of sparse matrix.
rusty1s's avatar
add doc  
rusty1s committed
16
17
        matrix (:class:`Tensor`): The dense matrix of same type as
            :obj:`value`.
rusty1s's avatar
docs  
rusty1s committed
18
19
20

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

rusty1s's avatar
cleanup  
rusty1s committed
22
    assert n == matrix.size(-2)
rusty1s's avatar
rusty1s committed
23

rusty1s's avatar
rusty1s committed
24
    row, col = index[0], index[1]
rusty1s's avatar
rusty1s committed
25
26
    matrix = matrix if matrix.dim() > 1 else matrix.unsqueeze(-1)

rusty1s's avatar
cleanup  
rusty1s committed
27
    out = matrix.index_select(-2, col)
rusty1s's avatar
rusty1s committed
28
    out = out * value.unsqueeze(-1)
29
    out = scatter_add(out, row, dim=-2, dim_size=m)
rusty1s's avatar
rusty1s committed
30
31

    return out