matmul.py 5.86 KB
Newer Older
rusty1s's avatar
matmul  
rusty1s committed
1
2
import warnings
import os.path as osp
rusty1s's avatar
rusty1s committed
3
from typing import Optional, Union, Tuple
rusty1s's avatar
matmul  
rusty1s committed
4

rusty1s's avatar
rusty1s committed
5
import torch
rusty1s's avatar
matmul  
rusty1s committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from torch_sparse.tensor import SparseTensor

try:
    torch.ops.load_library(
        osp.join(osp.dirname(osp.abspath(__file__)), '_spmm.so'))
except OSError:
    warnings.warn('Failed to load `spmm` binaries.')

    def spmm_sum_placeholder(row: Optional[torch.Tensor], rowptr: torch.Tensor,
                             col: torch.Tensor, value: Optional[torch.Tensor],
                             colptr: Optional[torch.Tensor],
                             csr2csc: Optional[torch.Tensor],
                             mat: torch.Tensor) -> torch.Tensor:
        raise ImportError
        return mat

22
23
24
25
26
27
28
29
30
31
    def spmm_mean_placeholder(row: Optional[torch.Tensor],
                              rowptr: torch.Tensor, col: torch.Tensor,
                              value: Optional[torch.Tensor],
                              rowcount: Optional[torch.Tensor],
                              colptr: Optional[torch.Tensor],
                              csr2csc: Optional[torch.Tensor],
                              mat: torch.Tensor) -> torch.Tensor:
        raise ImportError
        return mat

rusty1s's avatar
rusty1s committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
    def spmm_min_max_placeholder(rowptr: torch.Tensor, col: torch.Tensor,
                                 value: Optional[torch.Tensor],
                                 mat: torch.Tensor
                                 ) -> Tuple[torch.Tensor, torch.Tensor]:
        raise ImportError
        return mat, mat

    def spspmm_sum_placeholder(
            rowptrA: torch.Tensor, colA: torch.Tensor,
            valueA: Optional[torch.Tensor], rowptrB: torch.Tensor,
            colB: torch.Tensor, valueB: Optional[torch.Tensor], K: int
    ) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
        raise ImportError
        return rowptrA, colA, valueA

rusty1s's avatar
matmul  
rusty1s committed
47
    torch.ops.torch_sparse.spmm_sum = spmm_sum_placeholder
48
    torch.ops.torch_sparse.spmm_mean = spmm_mean_placeholder
rusty1s's avatar
rusty1s committed
49
50
51
    torch.ops.torch_sparse.spmm_min = spmm_min_max_placeholder
    torch.ops.torch_sparse.spmm_max = spmm_min_max_placeholder
    torch.ops.torch_sparse.spspmm_sum = spspmm_sum_placeholder
rusty1s's avatar
matmul  
rusty1s committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78


@torch.jit.script
def spmm_sum(src: SparseTensor, other: torch.Tensor) -> torch.Tensor:
    rowptr, col, value = src.csr()

    row = src.storage._row
    csr2csc = src.storage._csr2csc
    colptr = src.storage._colptr

    if value is not None and value.requires_grad:
        row = src.storage.row()

    if other.requires_grad:
        row = src.storage.row()
        csr2csc = src.storage.csr2csc()
        colptr = src.storage.colptr()

    return torch.ops.torch_sparse.spmm_sum(row, rowptr, col, value, colptr,
                                           csr2csc, other)


@torch.jit.script
def spmm_add(src: SparseTensor, other: torch.Tensor) -> torch.Tensor:
    return spmm_sum(src, other)


79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
@torch.jit.script
def spmm_mean(src: SparseTensor, other: torch.Tensor) -> torch.Tensor:
    rowptr, col, value = src.csr()

    row = src.storage._row
    rowcount = src.storage._rowcount
    csr2csc = src.storage._csr2csc
    colptr = src.storage._colptr

    if value is not None and value.requires_grad:
        row = src.storage.row()

    if other.requires_grad:
        row = src.storage.row()
        rowcount = src.storage.rowcount()
        csr2csc = src.storage.csr2csc()
        colptr = src.storage.colptr()

    return torch.ops.torch_sparse.spmm_mean(row, rowptr, col, value, rowcount,
                                            colptr, csr2csc, other)


rusty1s's avatar
rusty1s committed
101
102
103
104
105
106
107
108
109
110
111
112
113
114
@torch.jit.script
def spmm_min(src: SparseTensor,
             other: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
    rowptr, col, value = src.csr()
    return torch.ops.torch_sparse.spmm_min(rowptr, col, value, other)


@torch.jit.script
def spmm_max(src: SparseTensor,
             other: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
    rowptr, col, value = src.csr()
    return torch.ops.torch_sparse.spmm_max(rowptr, col, value, other)


rusty1s's avatar
matmul  
rusty1s committed
115
116
117
118
119
@torch.jit.script
def spmm(src: SparseTensor, other: torch.Tensor,
         reduce: str = "sum") -> torch.Tensor:
    if reduce == 'sum' or reduce == 'add':
        return spmm_sum(src, other)
120
121
    elif reduce == 'mean':
        return spmm_mean(src, other)
rusty1s's avatar
rusty1s committed
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
    elif reduce == 'min':
        return spmm_min(src, other)[0]
    elif reduce == 'max':
        return spmm_max(src, other)[0]
    else:
        raise ValueError


@torch.jit.script
def spspmm_sum(src: SparseTensor, other: SparseTensor) -> SparseTensor:
    rowptrA, colA, valueA = src.csr()
    rowptrB, colB, valueB = other.csr()
    M, K = src.sparse_size(0), other.sparse_size(1)
    rowptrC, colC, valueC = torch.ops.torch_sparse.spspmm_sum(
        rowptrA, colA, valueA, rowptrB, colB, valueB, K)
    return SparseTensor(row=None, rowptr=rowptrC, col=colC, value=valueC,
                        sparse_sizes=torch.Size([M, K]), is_sorted=True)


@torch.jit.script
def spspmm_add(src: SparseTensor, other: SparseTensor) -> SparseTensor:
    return spspmm_sum(src, other)


@torch.jit.script
def spspmm(src: SparseTensor, other: SparseTensor,
           reduce: str = "sum") -> SparseTensor:
    if reduce == 'sum' or reduce == 'add':
        return spspmm_sum(src, other)
    elif reduce == 'mean' or reduce == 'min' or reduce == 'max':
        raise NotImplementedError
rusty1s's avatar
matmul  
rusty1s committed
153
154
155
156
157
158
    else:
        raise ValueError


def matmul(src: SparseTensor, other: Union[torch.Tensor, SparseTensor],
           reduce: str = "sum"):
rusty1s's avatar
rusty1s committed
159
    if torch.is_tensor(other):
rusty1s's avatar
matmul  
rusty1s committed
160
        return spmm(src, other, reduce)
rusty1s's avatar
rusty1s committed
161
162
    elif isinstance(other, SparseTensor):
        return spspmm(src, other, reduce)
rusty1s's avatar
matmul  
rusty1s committed
163
164
165
166
167
    else:
        raise ValueError


SparseTensor.spmm = lambda self, other, reduce=None: spmm(self, other, reduce)
rusty1s's avatar
rusty1s committed
168
169
SparseTensor.spspmm = lambda self, other, reduce=None: spspmm(
    self, other, reduce)
rusty1s's avatar
matmul  
rusty1s committed
170
171
172
SparseTensor.matmul = lambda self, other, reduce=None: matmul(
    self, other, reduce)
SparseTensor.__matmul__ = lambda self, other: matmul(self, other, 'sum')