tensor.py 16.5 KB
Newer Older
rusty1s's avatar
rusty1s committed
1
2
3
4
5
from textwrap import indent

import torch
import scipy.sparse

rusty1s's avatar
rusty1s committed
6
from torch_sparse.storage import SparseStorage, get_layout
rusty1s's avatar
rusty1s committed
7

rusty1s's avatar
rusty1s committed
8
from torch_sparse.transpose import t
rusty1s's avatar
rusty1s committed
9
from torch_sparse.narrow import narrow
rusty1s's avatar
rusty1s committed
10
11
12
from torch_sparse.select import select
from torch_sparse.index_select import index_select, index_select_nnz
from torch_sparse.masked_select import masked_select, masked_select_nnz
rusty1s's avatar
rusty1s committed
13
import torch_sparse.reduce
rusty1s's avatar
rusty1s committed
14
from torch_sparse.diag import remove_diag, set_diag
rusty1s's avatar
rusty1s committed
15
from torch_sparse.matmul import matmul
rusty1s's avatar
rusty1s committed
16
from torch_sparse.add import add, add_, add_nnz, add_nnz_
rusty1s's avatar
rusty1s committed
17
from torch_sparse.mul import mul, mul_, mul_nnz, mul_nnz_
rusty1s's avatar
rusty1s committed
18
from torch_sparse.utils import is_scalar
rusty1s's avatar
rusty1s committed
19
20
21


class SparseTensor(object):
rusty1s's avatar
rusty1s committed
22
23
24
25
    def __init__(self, row=None, rowptr=None, col=None, value=None,
                 sparse_size=None, is_sorted=False):
        self.storage = SparseStorage(row=row, rowptr=rowptr, col=col,
                                     value=value, sparse_size=sparse_size,
rusty1s's avatar
rusty1s committed
26
                                     is_sorted=is_sorted)
rusty1s's avatar
rusty1s committed
27
28
29
30

    @classmethod
    def from_storage(self, storage):
        self = SparseTensor.__new__(SparseTensor)
rusty1s's avatar
rusty1s committed
31
        self.storage = storage
rusty1s's avatar
rusty1s committed
32
33
34
35
36
37
38
39
40
        return self

    @classmethod
    def from_dense(self, mat):
        if mat.dim() > 2:
            index = mat.abs().sum([i for i in range(2, mat.dim())]).nonzero()
        else:
            index = mat.nonzero()

rusty1s's avatar
rusty1s committed
41
42
43
        row, col = index.t().contiguous()
        return SparseTensor(row=row, col=col, value=mat[row, col],
                            sparse_size=mat.size()[:2], is_sorted=True)
rusty1s's avatar
rusty1s committed
44
45
46

    @classmethod
    def from_torch_sparse_coo_tensor(self, mat, is_sorted=False):
rusty1s's avatar
rusty1s committed
47
48
49
        row, col = mat._indices()
        return SparseTensor(row=row, col=col, value=mat._values(),
                            sparse_size=mat.size()[:2], is_sorted=is_sorted)
rusty1s's avatar
rusty1s committed
50
51
52
53
54
55
56

    @classmethod
    def from_scipy(self, mat):
        colptr = None
        if isinstance(mat, scipy.sparse.csc_matrix):
            colptr = torch.from_numpy(mat.indptr).to(torch.long)

rusty1s's avatar
rusty1s committed
57
        mat = mat.tocsr()  # Pre-sort.
rusty1s's avatar
rusty1s committed
58
59
60
61
62
        rowptr = torch.from_numpy(mat.indptr).to(torch.long)
        mat = mat.tocoo()
        row = torch.from_numpy(mat.row).to(torch.long)
        col = torch.from_numpy(mat.col).to(torch.long)
        value = torch.from_numpy(mat.data)
rusty1s's avatar
rusty1s committed
63
        sparse_size = mat.shape[:2]
rusty1s's avatar
rusty1s committed
64

rusty1s's avatar
rusty1s committed
65
66
67
        storage = SparseStorage(row=row, rowptr=rowptr, col=col, value=value,
                                sparse_size=sparse_size, colptr=colptr,
                                is_sorted=True)
rusty1s's avatar
rusty1s committed
68
69

        return SparseTensor.from_storage(storage)
rusty1s's avatar
rusty1s committed
70

rusty1s's avatar
rusty1s committed
71
    @classmethod
rusty1s's avatar
rusty1s committed
72
    def eye(self, M, N=None, device=None, dtype=None, has_value=True,
rusty1s's avatar
rusty1s committed
73
74
            fill_cache=False):
        N = M if N is None else N
rusty1s's avatar
rusty1s committed
75

rusty1s's avatar
rusty1s committed
76
77
78
79
80
        row = torch.arange(min(M, N), device=device)
        rowptr = torch.arange(M + 1, device=device)
        if M > N:
            rowptr[row.size(0) + 1:] = row.size(0)
        col = row
rusty1s's avatar
rusty1s committed
81
82

        value = None
rusty1s's avatar
rusty1s committed
83
84
        if has_value:
            value = torch.ones(row.size(0), dtype=dtype, device=device)
rusty1s's avatar
rusty1s committed
85

rusty1s's avatar
rusty1s committed
86
        rowcount = colptr = colcount = csr2csc = csc2csr = None
rusty1s's avatar
rusty1s committed
87
        if fill_cache:
rusty1s's avatar
rusty1s committed
88
            rowcount = row.new_ones(M)
rusty1s's avatar
rusty1s committed
89
            if M > N:
rusty1s's avatar
rusty1s committed
90
                rowcount[row.size(0):] = 0
rusty1s's avatar
rusty1s committed
91
            colptr = torch.arange(N + 1, device=device)
rusty1s's avatar
rusty1s committed
92
            colcount = col.new_ones(N)
rusty1s's avatar
rusty1s committed
93
            if N > M:
rusty1s's avatar
rusty1s committed
94
95
96
97
98
99
100
101
102
                colptr[col.size(0) + 1:] = col.size(0)
                colcount[col.size(0):] = 0
            csr2csc = csc2csr = row

        storage = SparseStorage(row=row, rowptr=rowptr, col=col, value=value,
                                sparse_size=torch.Size([M, N]),
                                rowcount=rowcount, colptr=colptr,
                                colcount=colcount, csr2csc=csr2csc,
                                csc2csr=csc2csr, is_sorted=True)
rusty1s's avatar
rusty1s committed
103
104
        return SparseTensor.from_storage(storage)

rusty1s's avatar
rusty1s committed
105
    def __copy__(self):
rusty1s's avatar
rusty1s committed
106
        return self.from_storage(self.storage)
rusty1s's avatar
rusty1s committed
107
108

    def clone(self):
rusty1s's avatar
rusty1s committed
109
        return self.from_storage(self.storage.clone())
rusty1s's avatar
rusty1s committed
110
111
112
113
114
115
116
117
118

    def __deepcopy__(self, memo):
        new_sparse_tensor = self.clone()
        memo[id(self)] = new_sparse_tensor
        return new_sparse_tensor

    # Formats #################################################################

    def coo(self):
rusty1s's avatar
rusty1s committed
119
        return self.storage.row, self.storage.col, self.storage.value
rusty1s's avatar
rusty1s committed
120
121

    def csr(self):
rusty1s's avatar
rusty1s committed
122
        return self.storage.rowptr, self.storage.col, self.storage.value
rusty1s's avatar
rusty1s committed
123
124

    def csc(self):
rusty1s's avatar
fixes  
rusty1s committed
125
        perm = self.storage.csr2csc  # Compute `csr2csc` first.
rusty1s's avatar
rusty1s committed
126
127
        return (self.storage.colptr, self.storage.row[perm],
                self.storage.value[perm] if self.has_value() else None)
rusty1s's avatar
rusty1s committed
128
129
130
131

    # Storage inheritance #####################################################

    def has_value(self):
rusty1s's avatar
rusty1s committed
132
        return self.storage.has_value()
rusty1s's avatar
rusty1s committed
133

rusty1s's avatar
rusty1s committed
134
135
    def set_value_(self, value, layout=None, dtype=None):
        self.storage.set_value_(value, layout, dtype)
rusty1s's avatar
rusty1s committed
136
137
        return self

rusty1s's avatar
rusty1s committed
138
139
    def set_value(self, value, layout=None, dtype=None):
        return self.from_storage(self.storage.set_value(value, layout, dtype))
rusty1s's avatar
rusty1s committed
140
141

    def sparse_size(self, dim=None):
rusty1s's avatar
rusty1s committed
142
143
        sparse_size = self.storage.sparse_size
        return sparse_size if dim is None else sparse_size[dim]
rusty1s's avatar
rusty1s committed
144

rusty1s's avatar
rusty1s committed
145
146
    def sparse_resize(self, *sizes):
        return self.from_storage(self.storage.sparse_resize(*sizes))
rusty1s's avatar
rusty1s committed
147
148

    def is_coalesced(self):
rusty1s's avatar
rusty1s committed
149
        return self.storage.is_coalesced()
rusty1s's avatar
rusty1s committed
150

rusty1s's avatar
rusty1s committed
151
152
    def coalesce(self, reduce='add'):
        return self.from_storage(self.storage.coalesce(reduce))
rusty1s's avatar
rusty1s committed
153
154

    def cached_keys(self):
rusty1s's avatar
rusty1s committed
155
        return self.storage.cached_keys()
rusty1s's avatar
rusty1s committed
156
157

    def fill_cache_(self, *args):
rusty1s's avatar
rusty1s committed
158
        self.storage.fill_cache_(*args)
rusty1s's avatar
rusty1s committed
159
160
161
        return self

    def clear_cache_(self, *args):
rusty1s's avatar
rusty1s committed
162
        self.storage.clear_cache_(*args)
rusty1s's avatar
rusty1s committed
163
164
165
166
        return self

    # Utility functions #######################################################

rusty1s's avatar
rusty1s committed
167
168
169
    def dim(self):
        return len(self.size())

rusty1s's avatar
rusty1s committed
170
171
    def size(self, dim=None):
        size = self.sparse_size()
rusty1s's avatar
rusty1s committed
172
        size += self.storage.value.size()[1:] if self.has_value() else ()
rusty1s's avatar
rusty1s committed
173
174
175
176
177
178
179
        return size if dim is None else size[dim]

    @property
    def shape(self):
        return self.size()

    def nnz(self):
rusty1s's avatar
rusty1s committed
180
        return self.storage.col.numel()
rusty1s's avatar
rusty1s committed
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203

    def density(self):
        return self.nnz() / (self.sparse_size(0) * self.sparse_size(1))

    def sparsity(self):
        return 1 - self.density()

    def avg_row_length(self):
        return self.nnz() / self.sparse_size(0)

    def avg_col_length(self):
        return self.nnz() / self.sparse_size(1)

    def numel(self):
        return self.value.numel() if self.has_value() else self.nnz()

    def is_quadratic(self):
        return self.sparse_size(0) == self.sparse_size(1)

    def is_symmetric(self):
        if not self.is_quadratic:
            return False

rusty1s's avatar
rusty1s committed
204
205
206
207
208
209
210
211
212
213
        rowptr, col, value1 = self.csr()
        colptr, row, value2 = self.csc()

        if (rowptr != colptr).any() or (col != row).any():
            return False

        if not self.has_value():
            return True

        return (value1 == value2).all().item()
rusty1s's avatar
rusty1s committed
214
215

    def detach_(self):
rusty1s's avatar
rusty1s committed
216
        self.storage.apply_(lambda x: x.detach_())
rusty1s's avatar
rusty1s committed
217
218
219
        return self

    def detach(self):
rusty1s's avatar
rusty1s committed
220
        return self.from_storage(self.storage.apply(lambda x: x.detach()))
rusty1s's avatar
rusty1s committed
221

rusty1s's avatar
rusty1s committed
222
223
224
225
    @property
    def requires_grad(self):
        return self.storage.value.requires_grad if self.has_value() else False

rusty1s's avatar
rusty1s committed
226
227
228
229
    def requires_grad_(self, requires_grad=True, dtype=None):
        if requires_grad and not self.has_value():
            self.storage.set_value_(1, dtype=dtype)

rusty1s's avatar
rusty1s committed
230
231
        if self.has_value():
            self.storage.value.requires_grad_(requires_grad)
rusty1s's avatar
rusty1s committed
232

rusty1s's avatar
rusty1s committed
233
234
        return self

rusty1s's avatar
rusty1s committed
235
    def pin_memory(self):
rusty1s's avatar
rusty1s committed
236
        return self.from_storage(self.storage.apply(lambda x: x.pin_memory()))
rusty1s's avatar
rusty1s committed
237
238

    def is_pinned(self):
rusty1s's avatar
rusty1s committed
239
        return all(self.storage.map(lambda x: x.is_pinned()))
rusty1s's avatar
rusty1s committed
240
241

    def share_memory_(self):
rusty1s's avatar
rusty1s committed
242
        self.storage.apply_(lambda x: x.share_memory_())
rusty1s's avatar
rusty1s committed
243
244
245
        return self

    def is_shared(self):
rusty1s's avatar
rusty1s committed
246
        return all(self.storage.map(lambda x: x.is_shared()))
rusty1s's avatar
rusty1s committed
247
248
249

    @property
    def device(self):
rusty1s's avatar
rusty1s committed
250
        return self.storage.col.device
rusty1s's avatar
rusty1s committed
251
252

    def cpu(self):
rusty1s's avatar
rusty1s committed
253
        return self.from_storage(self.storage.apply(lambda x: x.cpu()))
rusty1s's avatar
rusty1s committed
254
255

    def cuda(self, device=None, non_blocking=False, **kwargs):
rusty1s's avatar
rusty1s committed
256
257
        storage = self.storage.apply(
            lambda x: x.cuda(device, non_blocking, **kwargs))
rusty1s's avatar
rusty1s committed
258
        return self.from_storage(storage)
rusty1s's avatar
rusty1s committed
259
260
261

    @property
    def is_cuda(self):
rusty1s's avatar
rusty1s committed
262
        return self.storage.col.is_cuda
rusty1s's avatar
rusty1s committed
263
264
265

    @property
    def dtype(self):
rusty1s's avatar
rusty1s committed
266
        return self.storage.value.dtype if self.has_value() else None
rusty1s's avatar
rusty1s committed
267
268

    def is_floating_point(self):
rusty1s's avatar
rusty1s committed
269
        value = self.storage.value
rusty1s's avatar
rusty1s committed
270
271
272
273
274
275
276
277
278
        return self.has_value() and torch.is_floating_point(value)

    def type(self, dtype=None, non_blocking=False, **kwargs):
        if dtype is None:
            return self.dtype

        if dtype == self.dtype:
            return self

rusty1s's avatar
rusty1s committed
279
280
        storage = self.storage.apply_value(
            lambda x: x.type(dtype, non_blocking, **kwargs))
rusty1s's avatar
rusty1s committed
281
282

        return self.from_storage(storage)
rusty1s's avatar
rusty1s committed
283
284

    def to(self, *args, **kwargs):
rusty1s's avatar
rusty1s committed
285
286
287
        args = list(args)

        non_blocking = getattr(kwargs, 'non_blocking', False)
rusty1s's avatar
rusty1s committed
288

rusty1s's avatar
rusty1s committed
289
        storage = None
rusty1s's avatar
rusty1s committed
290
291
292
        if 'device' in kwargs:
            device = kwargs['device']
            del kwargs['device']
rusty1s's avatar
rusty1s committed
293
294
295
296
297
298
299
300
            storage = self.storage.apply(
                lambda x: x.to(device, non_blocking=non_blocking))
        else:
            for arg in args[:]:
                if isinstance(arg, str) or isinstance(arg, torch.device):
                    storage = self.storage.apply(
                        lambda x: x.to(arg, non_blocking=non_blocking))
                    args.remove(arg)
rusty1s's avatar
rusty1s committed
301

rusty1s's avatar
rusty1s committed
302
        storage = self.storage if storage is None else storage
rusty1s's avatar
rusty1s committed
303
304

        if len(args) > 0 or len(kwargs) > 0:
rusty1s's avatar
rusty1s committed
305
            storage = storage.apply_value(lambda x: x.type(*args, **kwargs))
rusty1s's avatar
rusty1s committed
306

rusty1s's avatar
rusty1s committed
307
        if storage == self.storage:  # Nothing has been changed...
rusty1s's avatar
rusty1s committed
308
309
310
            return self
        else:
            return self.from_storage(storage)
rusty1s's avatar
rusty1s committed
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345

    def bfloat16(self):
        return self.type(torch.bfloat16)

    def bool(self):
        return self.type(torch.bool)

    def byte(self):
        return self.type(torch.byte)

    def char(self):
        return self.type(torch.char)

    def half(self):
        return self.type(torch.half)

    def float(self):
        return self.type(torch.float)

    def double(self):
        return self.type(torch.double)

    def short(self):
        return self.type(torch.short)

    def int(self):
        return self.type(torch.int)

    def long(self):
        return self.type(torch.long)

    # Conversions #############################################################

    def to_dense(self, dtype=None):
        dtype = dtype or self.dtype
rusty1s's avatar
rusty1s committed
346
        row, col, value = self.coo()
rusty1s's avatar
rusty1s committed
347
348
349
350
351
        mat = torch.zeros(self.size(), dtype=dtype, device=self.device)
        mat[row, col] = value if self.has_value() else 1
        return mat

    def to_torch_sparse_coo_tensor(self, dtype=None, requires_grad=False):
rusty1s's avatar
rusty1s committed
352
353
354
355
356
357
358
        row, col, value = self.coo()
        index = torch.stack([row, col], dim=0)
        if value is None:
            value = torch.ones(self.nnz(), dtype=dtype, device=self.device)
        return torch.sparse_coo_tensor(index, value, self.size(),
                                       device=self.device,
                                       requires_grad=requires_grad)
rusty1s's avatar
rusty1s committed
359

rusty1s's avatar
rusty1s committed
360
    def to_scipy(self, layout=None, dtype=None):
rusty1s's avatar
rusty1s committed
361
        assert self.dim() == 2
rusty1s's avatar
rusty1s committed
362
        layout = get_layout(layout)
rusty1s's avatar
rusty1s committed
363

rusty1s's avatar
rusty1s committed
364
365
        if not self.has_value():
            ones = torch.ones(self.nnz(), dtype=dtype).numpy()
rusty1s's avatar
rusty1s committed
366
367

        if layout == 'coo':
rusty1s's avatar
rusty1s committed
368
            row, col, value = self.coo()
rusty1s's avatar
rusty1s committed
369
370
371
            row = row.detach().cpu().numpy()
            col = col.detach().cpu().numpy()
            value = value.detach().cpu().numpy() if self.has_value() else ones
rusty1s's avatar
rusty1s committed
372
373
            return scipy.sparse.coo_matrix((value, (row, col)), self.size())
        elif layout == 'csr':
rusty1s's avatar
rusty1s committed
374
375
376
377
            rowptr, col, value = self.csr()
            rowptr = rowptr.detach().cpu().numpy()
            col = col.detach().cpu().numpy()
            value = value.detach().cpu().numpy() if self.has_value() else ones
rusty1s's avatar
rusty1s committed
378
379
            return scipy.sparse.csr_matrix((value, col, rowptr), self.size())
        elif layout == 'csc':
rusty1s's avatar
rusty1s committed
380
381
382
383
            colptr, row, value = self.csc()
            colptr = colptr.detach().cpu().numpy()
            row = row.detach().cpu().numpy()
            value = value.detach().cpu().numpy() if self.has_value() else ones
rusty1s's avatar
rusty1s committed
384
385
            return scipy.sparse.csc_matrix((value, row, colptr), self.size())

rusty1s's avatar
rusty1s committed
386
387
388
389
    # Standard Operators ######################################################

    def __getitem__(self, index):
        index = list(index) if isinstance(index, tuple) else [index]
rusty1s's avatar
typo  
rusty1s committed
390
        # More than one `Ellipsis` is not allowed...
rusty1s's avatar
rusty1s committed
391
        if len([i for i in index if not torch.is_tensor(i) and i == ...]) > 1:
rusty1s's avatar
rusty1s committed
392
            raise SyntaxError
rusty1s's avatar
rusty1s committed
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421

        dim = 0
        out = self
        while len(index) > 0:
            item = index.pop(0)
            if isinstance(item, int):
                out = out.select(dim, item)
                dim += 1
            elif isinstance(item, slice):
                if item.step is not None:
                    raise ValueError('Step parameter not yet supported.')

                start = 0 if item.start is None else item.start
                start = self.size(dim) + start if start < 0 else start

                stop = self.size(dim) if item.stop is None else item.stop
                stop = self.size(dim) + stop if stop < 0 else stop

                out = out.narrow(dim, start, max(stop - start, 0))
                dim += 1
            elif torch.is_tensor(item):
                if item.dtype == torch.bool:
                    out = out.masked_select(dim, item)
                    dim += 1
                elif item.dtype == torch.long:
                    out = out.index_select(dim, item)
                    dim += 1
            elif item == Ellipsis:
                if self.dim() - len(index) < dim:
rusty1s's avatar
typo  
rusty1s committed
422
                    raise SyntaxError
rusty1s's avatar
rusty1s committed
423
424
                dim = self.dim() - len(index)
            else:
rusty1s's avatar
typo  
rusty1s committed
425
                raise SyntaxError
rusty1s's avatar
rusty1s committed
426
427
428

        return out

rusty1s's avatar
rusty1s committed
429
430
431
432
433
434
435
436
437
    def __add__(self, other):
        return self.add(other)

    def __radd__(self, other):
        return self.add(other)

    def __iadd__(self, other):
        return self.add_(other)

rusty1s's avatar
typos  
rusty1s committed
438
439
440
441
442
443
444
445
446
447
448
    def __mul__(self, other):
        return self.mul(other)

    def __rmul__(self, other):
        return self.mul(other)

    def __imul__(self, other):
        return self.mul_(other)

    def __matmul__(self, other):
        return matmul(self, other, reduce='sum')
rusty1s's avatar
rusty1s committed
449

rusty1s's avatar
rusty1s committed
450
451
452
453
    # String Reputation #######################################################

    def __repr__(self):
        i = ' ' * 6
rusty1s's avatar
rusty1s committed
454
455
456
457
        row, col, value = self.coo()
        infos = []
        infos += [f'row={indent(row.__repr__(), i)[len(i):]}']
        infos += [f'col={indent(col.__repr__(), i)[len(i):]}']
rusty1s's avatar
rusty1s committed
458
459

        if self.has_value():
rusty1s's avatar
rusty1s committed
460
            infos += [f'val={indent(value.__repr__(), i)[len(i):]}']
rusty1s's avatar
rusty1s committed
461
462
463
464
465
466
467
468
469
470
471
472
473

        infos += [
            f'size={tuple(self.size())}, '
            f'nnz={self.nnz()}, '
            f'density={100 * self.density():.02f}%'
        ]
        infos = ',\n'.join(infos)

        i = ' ' * (len(self.__class__.__name__) + 1)
        return f'{self.__class__.__name__}({indent(infos, i)[len(i):]})'


# Bindings ####################################################################
rusty1s's avatar
rusty1s committed
474

rusty1s's avatar
rusty1s committed
475
SparseTensor.t = t
rusty1s's avatar
rusty1s committed
476
SparseTensor.narrow = narrow
rusty1s's avatar
rusty1s committed
477
478
479
480
481
SparseTensor.select = select
SparseTensor.index_select = index_select
SparseTensor.index_select_nnz = index_select_nnz
SparseTensor.masked_select = masked_select
SparseTensor.masked_select_nnz = masked_select_nnz
rusty1s's avatar
rusty1s committed
482
SparseTensor.reduction = torch_sparse.reduce.reduction
rusty1s's avatar
rusty1s committed
483
484
485
486
SparseTensor.sum = torch_sparse.reduce.sum
SparseTensor.mean = torch_sparse.reduce.mean
SparseTensor.min = torch_sparse.reduce.min
SparseTensor.max = torch_sparse.reduce.max
rusty1s's avatar
rusty1s committed
487
488
489
SparseTensor.remove_diag = remove_diag
SparseTensor.set_diag = set_diag
SparseTensor.matmul = matmul
rusty1s's avatar
rusty1s committed
490
491
492
493
SparseTensor.add = add
SparseTensor.add_ = add_
SparseTensor.add_nnz = add_nnz
SparseTensor.add_nnz_ = add_nnz_
rusty1s's avatar
rusty1s committed
494
495
496
497
498
499
500
501
SparseTensor.mul = mul
SparseTensor.mul_ = mul_
SparseTensor.mul_nnz = mul_nnz
SparseTensor.mul_nnz_ = mul_nnz_

# Fix for PyTorch<=1.3 (https://github.com/pytorch/pytorch/pull/31769):
TORCH_MAJOR = int(torch.__version__.split('.')[0])
TORCH_MINOR = int(torch.__version__.split('.')[1])
rusty1s's avatar
typo  
rusty1s committed
502
if (TORCH_MAJOR < 1) or (TORCH_MAJOR == 1 and TORCH_MINOR < 4):
rusty1s's avatar
rusty1s committed
503
504

    def add(self, other):
rusty1s's avatar
rusty1s committed
505
506
507
        if torch.is_tensor(other) or is_scalar(other):
            return self.add(other)
        return NotImplemented
rusty1s's avatar
rusty1s committed
508
509

    def mul(self, other):
rusty1s's avatar
rusty1s committed
510
511
512
        if torch.is_tensor(other) or is_scalar(other):
            return self.mul(other)
        return NotImplemented
rusty1s's avatar
rusty1s committed
513
514

    torch.Tensor.__add__ = add
rusty1s's avatar
rusty1s committed
515
    torch.Tensor.__mul__ = mul