storage.py 7.42 KB
Newer Older
rusty1s's avatar
rusty1s committed
1
import warnings
rusty1s's avatar
rusty1s committed
2

rusty1s's avatar
rusty1s committed
3
4
5
6
import torch
from torch_scatter import scatter_add, segment_add


rusty1s's avatar
rusty1s committed
7
8
def optional(func, src):
    return func(src) if src is not None else src
rusty1s's avatar
rusty1s committed
9
10


rusty1s's avatar
rusty1s committed
11
12
13
class cached_property(object):
    def __init__(self, func):
        self.func = func
rusty1s's avatar
sorting  
rusty1s committed
14

rusty1s's avatar
rusty1s committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    def __get__(self, obj, cls):
        value = getattr(obj, f'_{self.func.__name__}', None)
        if value is None:
            value = self.func(obj)
            setattr(obj, f'_{self.func.__name__}', value)
        return value


class SparseStorage(object):
    cache_keys = ['rowptr', 'colptr', 'csr_to_csc', 'csc_to_csr']

    def __init__(self, index, value=None, sparse_size=None, rowptr=None,
                 colptr=None, csr_to_csc=None, csc_to_csr=None,
                 is_sorted=False):

        assert index.dtype == torch.long
        assert index.dim() == 2 and index.size(0) == 2
rusty1s's avatar
rusty1s committed
32
33

        if value is not None:
rusty1s's avatar
rusty1s committed
34
35
            assert value.device == index.device
            assert value.size(0) == index.size(1)
rusty1s's avatar
rusty1s committed
36
37
            value = value.contiguous()

rusty1s's avatar
rusty1s committed
38
39
40
41
42
        if sparse_size is None:
            sparse_size = torch.Size((index.max(dim=-1)[0] + 1).tolist())

        if rowptr is not None:
            assert rowptr.dtype == torch.long and rowptr.device == index.device
rusty1s's avatar
rusty1s committed
43
            assert rowptr.dim() == 1 and rowptr.numel() - 1 == sparse_size[0]
rusty1s's avatar
rusty1s committed
44

rusty1s's avatar
rusty1s committed
45
46
        if colptr is not None:
            assert colptr.dtype == torch.long and colptr.device == index.device
rusty1s's avatar
rusty1s committed
47
            assert colptr.dim() == 1 and colptr.numel() - 1 == sparse_size[1]
rusty1s's avatar
rusty1s committed
48

rusty1s's avatar
rusty1s committed
49
50
51
52
53
        if csr_to_csc is not None:
            assert csr_to_csc.dtype == torch.long
            assert csr_to_csc.device == index.device
            assert csr_to_csc.dim() == 1
            assert csr_to_csc.numel() == index.size(1)
rusty1s's avatar
rusty1s committed
54

rusty1s's avatar
rusty1s committed
55
56
57
58
59
        if csc_to_csr is not None:
            assert csc_to_csr.dtype == torch.long
            assert csc_to_csr.device == index.device
            assert csc_to_csr.dim() == 1
            assert csc_to_csr.numel() == index.size(1)
rusty1s's avatar
rusty1s committed
60

rusty1s's avatar
rusty1s committed
61
62
63
64
65
66
67
68
69
70
71
        if not is_sorted:
            idx = sparse_size[1] * index[0] + index[1]
            # Only sort if necessary...
            if (idx <= torch.cat([idx.new_zeros(1), idx[:-1]], dim=0)).any():
                perm = idx.argsort()
                index = index[:, perm]
                value = None if value is None else value[perm]
                rowptr = None
                colptr = None
                csr_to_csc = None
                csc_to_csr = None
rusty1s's avatar
rusty1s committed
72

rusty1s's avatar
rusty1s committed
73
74
75
76
77
78
79
        self._index = index
        self._value = value
        self._sparse_size = sparse_size
        self._rowptr = rowptr
        self._colptr = colptr
        self._csr_to_csc = csr_to_csc
        self._csc_to_csr = csc_to_csr
rusty1s's avatar
rusty1s committed
80
81

    @property
rusty1s's avatar
rusty1s committed
82
83
    def index(self):
        return self._index
rusty1s's avatar
rusty1s committed
84
85

    @property
rusty1s's avatar
rusty1s committed
86
87
    def row(self):
        return self._index[0]
rusty1s's avatar
rusty1s committed
88
89

    @property
rusty1s's avatar
rusty1s committed
90
91
    def col(self):
        return self._index[1]
rusty1s's avatar
rusty1s committed
92
93

    @property
rusty1s's avatar
rusty1s committed
94
95
    def has_value(self):
        return self._value is not None
rusty1s's avatar
rusty1s committed
96
97

    @property
rusty1s's avatar
rusty1s committed
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
    def value(self):
        return self._value

    def set_value_(self, value, layout=None):
        if layout is None:
            layout = 'coo'
            warnings.warn('`layout` argument unset, using default layout '
                          '"coo". This may lead to unexpected behaviour.')
        assert layout in ['coo', 'csr', 'csc']
        assert value.device == self._index.device
        assert value.size(0) == self._index.size(1)
        if value is not None and layout == 'csc':
            value = value[self.csc_to_csr]
        return self.apply_value_(lambda x: value)

    def set_value(self, value, layout=None):
        if layout is None:
            layout = 'coo'
            warnings.warn('`layout` argument unset, using default layout '
                          '"coo". This may lead to unexpected behaviour.')
        assert layout in ['coo', 'csr', 'csc']
        assert value.device == self._index.device
        assert value.size(0) == self._index.size(1)
        if value is not None and layout == 'csc':
            value = value[self.csc_to_csr]
        return self.apply_value(lambda x: value)
rusty1s's avatar
rusty1s committed
124
125

    def sparse_size(self, dim=None):
rusty1s's avatar
rusty1s committed
126
        return self._sparse_size if dim is None else self._sparse_size[dim]
rusty1s's avatar
rusty1s committed
127
128
129

    def sparse_resize_(self, *sizes):
        assert len(sizes) == 2
rusty1s's avatar
rusty1s committed
130
        self._sparse_size == sizes
rusty1s's avatar
rusty1s committed
131
        return self
rusty1s's avatar
rusty1s committed
132

rusty1s's avatar
rusty1s committed
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
    @cached_property
    def rowptr(self):
        row = self.row
        ones = torch.ones_like(row)
        out_deg = segment_add(ones, row, dim=0, dim_size=self._sparse_size[0])
        return torch.cat([row.new_zeros(1), out_deg.cumsum(0)], dim=0)

    @cached_property
    def colptr(self):
        col = self.col
        ones = torch.ones_like(col)
        in_deg = scatter_add(ones, col, dim=0, dim_size=self._sparse_size[1])
        return torch.cat([col.new_zeros(1), in_deg.cumsum(0)], dim=0)

    @cached_property
    def csr_to_csc(self):
        idx = self._sparse_size[0] * self.col + self.row
        return idx.argsort()

    @cached_property
    def csc_to_csr(self):
        return self.csr_to_csc.argsort()

    def compute_cache_(self, *args):
        for arg in args or self.cache_keys:
            getattr(self, arg)
rusty1s's avatar
rusty1s committed
159
        return self
rusty1s's avatar
rusty1s committed
160

rusty1s's avatar
rusty1s committed
161
162
163
164
    def clear_cache_(self, *args):
        for arg in args or self.cache_keys:
            setattr(self, f'_{arg}', None)
        return self
rusty1s's avatar
rusty1s committed
165

rusty1s's avatar
test  
rusty1s committed
166
167
168
169
170
171
172
173
174
175
176
177
178
179
    def clone(self):
        return self.apply(lambda x: x.clone())

    def __copy__(self):
        return self.clone()

    def __deepcopy__(self, memo):
        memo = memo.setdefault('SparseStorage', {})
        if self._cdata in memo:
            return memo[self._cdata]
        new_storage = self.clone()
        memo[self._cdata] = new_storage
        return new_storage

rusty1s's avatar
rusty1s committed
180
181
    def apply_value_(self, func):
        self._value = optional(func, self._value)
rusty1s's avatar
rusty1s committed
182
        return self
rusty1s's avatar
rusty1s committed
183

rusty1s's avatar
rusty1s committed
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
    def apply_value(self, func):
        return self.__class__(
            self._index,
            optional(func, self._value),
            self._sparse_size,
            self._rowptr,
            self._colptr,
            self._csr_to_csc,
            self._csc_to_csr,
            is_sorted=True,
        )

    def apply_(self, func):
        self._index = func(self._index)
        self._value = optional(func, self._value)
        for key in self.cache_keys:
            setattr(self, f'_{key}', optional(func, getattr(self, f'_{key}')))

    def apply(self, func):
        return self.__class__(
            func(self._index),
            optional(func, self._value),
            self._sparse_size,
            optional(func, self._rowptr),
            optional(func, self._colptr),
            optional(func, self._csr_to_csc),
            optional(func, self._csc_to_csr),
            is_sorted=True,
        )

rusty1s's avatar
rusty1s committed
214
215

if __name__ == '__main__':
rusty1s's avatar
test  
rusty1s committed
216
    from torch_geometric.datasets import Reddit, Planetoid  # noqa
rusty1s's avatar
rusty1s committed
217
    import time  # noqa
rusty1s's avatar
test  
rusty1s committed
218
    import copy  # noqa
rusty1s's avatar
rusty1s committed
219
220

    device = 'cuda' if torch.cuda.is_available() else 'cpu'
rusty1s's avatar
test  
rusty1s committed
221
222
    # dataset = Reddit('/tmp/Reddit')
    dataset = Planetoid('/tmp/Cora', 'Cora')
rusty1s's avatar
rusty1s committed
223
224
    data = dataset[0].to(device)
    edge_index = data.edge_index
rusty1s's avatar
sorting  
rusty1s committed
225

rusty1s's avatar
rusty1s committed
226
227
228
229
230
    storage = SparseStorage(edge_index, is_sorted=True)
    t = time.perf_counter()
    storage.compute_cache_()
    print(time.perf_counter() - t)
    t = time.perf_counter()
rusty1s's avatar
test  
rusty1s committed
231
    storage.clear_cache_()
rusty1s's avatar
rusty1s committed
232
233
    storage.compute_cache_()
    print(time.perf_counter() - t)
rusty1s's avatar
test  
rusty1s committed
234
235
236
237
238
239
240
241
242
    print(storage)
    storage = storage.clone()
    print(storage)
    # storage = copy.copy(storage)
    # print(storage)
    # storage = copy.deepcopy(storage)
    # print(storage)
    storage.compute_cache_()
    storage.clear_cache_()