tensor.py 20 KB
Newer Older
rusty1s's avatar
repr  
rusty1s committed
1
from textwrap import indent
rusty1s's avatar
typing  
rusty1s committed
2
from typing import Optional, List, Tuple, Dict, Union, Any
rusty1s's avatar
rusty1s committed
3
4
5
6

import torch
import scipy.sparse

rusty1s's avatar
rusty1s committed
7
from torch_sparse.storage import SparseStorage, get_layout
rusty1s's avatar
rusty1s committed
8
from torch_sparse.utils import is_scalar
rusty1s's avatar
rusty1s committed
9
10


rusty1s's avatar
rusty1s committed
11
@torch.jit.script
rusty1s's avatar
rusty1s committed
12
class SparseTensor(object):
rusty1s's avatar
rusty1s committed
13
14
    storage: SparseStorage

rusty1s's avatar
rusty1s committed
15
16
    def __init__(self,
                 row: Optional[torch.Tensor] = None,
rusty1s's avatar
rusty1s committed
17
18
19
                 rowptr: Optional[torch.Tensor] = None,
                 col: Optional[torch.Tensor] = None,
                 value: Optional[torch.Tensor] = None,
rusty1s's avatar
rusty1s committed
20
21
                 sparse_sizes: Optional[Tuple[int, int]] = None,
                 is_sorted: bool = False):
rusty1s's avatar
rusty1s committed
22
23
24
25
26
27
28
29
30
31
32
33
        self.storage = SparseStorage(
            row=row,
            rowptr=rowptr,
            col=col,
            value=value,
            sparse_sizes=sparse_sizes,
            rowcount=None,
            colptr=None,
            colcount=None,
            csr2csc=None,
            csc2csr=None,
            is_sorted=is_sorted)
rusty1s's avatar
rusty1s committed
34
35

    @classmethod
rusty1s's avatar
rusty1s committed
36
    def from_storage(self, storage: SparseStorage):
rusty1s's avatar
rusty1s committed
37
        self = SparseTensor.__new__(SparseTensor)
rusty1s's avatar
rusty1s committed
38
        self.storage = storage
rusty1s's avatar
rusty1s committed
39
40
41
        return self

    @classmethod
rusty1s's avatar
rusty1s committed
42
    def from_dense(self, mat: torch.Tensor, has_value: bool = True):
rusty1s's avatar
rusty1s committed
43
44
45
46
        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
47
        index = index.t()
rusty1s's avatar
rusty1s committed
48

rusty1s's avatar
rusty1s committed
49
50
51
52
53
54
55
        row = index[0]
        col = index[1]

        value: Optional[torch.Tensor] = None
        if has_value:
            value = mat[row, col]

rusty1s's avatar
rusty1s committed
56
57
58
59
60
61
62
        return SparseTensor(
            row=row,
            rowptr=None,
            col=col,
            value=value,
            sparse_sizes=(mat.size(0), mat.size(1)),
            is_sorted=True)
rusty1s's avatar
rusty1s committed
63
64

    @classmethod
rusty1s's avatar
rusty1s committed
65
66
    def from_torch_sparse_coo_tensor(self,
                                     mat: torch.Tensor,
rusty1s's avatar
rusty1s committed
67
                                     has_value: bool = True):
rusty1s's avatar
rusty1s committed
68
69
70
        mat = mat.coalesce()
        index = mat._indices()
        row, col = index[0], index[1]
rusty1s's avatar
rusty1s committed
71
72
73
74
75

        value: Optional[torch.Tensor] = None
        if has_value:
            value = mat._values()

rusty1s's avatar
rusty1s committed
76
77
78
79
80
81
82
        return SparseTensor(
            row=row,
            rowptr=None,
            col=col,
            value=value,
            sparse_sizes=(mat.size(0), mat.size(1)),
            is_sorted=True)
rusty1s's avatar
rusty1s committed
83
84

    @classmethod
rusty1s's avatar
rusty1s committed
85
86
87
88
89
    def eye(self,
            M: int,
            N: Optional[int] = None,
            options: Optional[torch.Tensor] = None,
            has_value: bool = True,
rusty1s's avatar
rusty1s committed
90
            fill_cache: bool = False):
rusty1s's avatar
rusty1s committed
91

rusty1s's avatar
rusty1s committed
92
        N = M if N is None else N
rusty1s's avatar
rusty1s committed
93

rusty1s's avatar
rusty1s committed
94
95
96
97
        if options is not None:
            row = torch.arange(min(M, N), device=options.device)
        else:
            row = torch.arange(min(M, N))
rusty1s's avatar
rusty1s committed
98
        col = row
rusty1s's avatar
rusty1s committed
99

rusty1s's avatar
rusty1s committed
100
101
        rowptr = torch.arange(M + 1, dtype=torch.long, device=row.device)
        if M > N:
rusty1s's avatar
rusty1s committed
102
            rowptr[N + 1:] = N
rusty1s's avatar
rusty1s committed
103
104

        value: Optional[torch.Tensor] = None
rusty1s's avatar
rusty1s committed
105
        if has_value:
rusty1s's avatar
rusty1s committed
106
            if options is not None:
rusty1s's avatar
rusty1s committed
107
108
                value = torch.ones(
                    row.numel(), dtype=options.dtype, device=row.device)
rusty1s's avatar
rusty1s committed
109
110
111
112
113
114
115
116
            else:
                value = torch.ones(row.numel(), device=row.device)

        rowcount: Optional[torch.Tensor] = None
        colptr: Optional[torch.Tensor] = None
        colcount: Optional[torch.Tensor] = None
        csr2csc: Optional[torch.Tensor] = None
        csc2csr: Optional[torch.Tensor] = None
rusty1s's avatar
rusty1s committed
117
118

        if fill_cache:
rusty1s's avatar
rusty1s committed
119
            rowcount = torch.ones(M, dtype=torch.long, device=row.device)
rusty1s's avatar
rusty1s committed
120
            if M > N:
rusty1s's avatar
rusty1s committed
121
122
123
124
                rowcount[N:] = 0

            colptr = torch.arange(N + 1, dtype=torch.long, device=row.device)
            colcount = torch.ones(N, dtype=torch.long, device=row.device)
rusty1s's avatar
rusty1s committed
125
            if N > M:
rusty1s's avatar
rusty1s committed
126
127
                colptr[M + 1:] = M
                colcount[M:] = 0
rusty1s's avatar
rusty1s committed
128
129
            csr2csc = csc2csr = row

rusty1s's avatar
rusty1s committed
130
        storage: SparseStorage = SparseStorage(
rusty1s's avatar
rusty1s committed
131
132
133
134
135
136
137
138
139
140
141
            row=row,
            rowptr=rowptr,
            col=col,
            value=value,
            sparse_sizes=(M, N),
            rowcount=rowcount,
            colptr=colptr,
            colcount=colcount,
            csr2csc=csr2csc,
            csc2csr=csc2csr,
            is_sorted=True)
rusty1s's avatar
rusty1s committed
142

rusty1s's avatar
rusty1s committed
143
144
145
146
147
        self = SparseTensor.__new__(SparseTensor)
        self.storage = storage
        return self

    def copy(self):
rusty1s's avatar
rusty1s committed
148
        return self.from_storage(self.storage)
rusty1s's avatar
rusty1s committed
149
150

    def clone(self):
rusty1s's avatar
rusty1s committed
151
        return self.from_storage(self.storage.clone())
rusty1s's avatar
rusty1s committed
152

rusty1s's avatar
rusty1s committed
153
154
155
156
157
158
159
160
161
162
    def type_as(self, tensor=torch.Tensor):
        value = self.storage._value
        if value is None or tensor.dtype == value.dtype:
            return self
        return self.from_storage(self.storage.type_as(tensor))

    def device_as(self, tensor: torch.Tensor, non_blocking: bool = False):
        if tensor.device == self.device():
            return self
        return self.from_storage(self.storage.device_as(tensor, non_blocking))
rusty1s's avatar
rusty1s committed
163
164
165

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

rusty1s's avatar
rusty1s committed
166
167
    def coo(self) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
        return self.storage.row(), self.storage.col(), self.storage.value()
rusty1s's avatar
rusty1s committed
168

rusty1s's avatar
rusty1s committed
169
170
    def csr(self) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
        return self.storage.rowptr(), self.storage.col(), self.storage.value()
rusty1s's avatar
rusty1s committed
171

rusty1s's avatar
rusty1s committed
172
173
174
175
176
177
    def csc(self) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
        perm = self.storage.csr2csc()
        value = self.storage.value()
        if value is not None:
            value = value[perm]
        return self.storage.colptr(), self.storage.row()[perm], value
rusty1s's avatar
rusty1s committed
178
179
180

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

rusty1s's avatar
rusty1s committed
181
    def has_value(self) -> bool:
rusty1s's avatar
rusty1s committed
182
        return self.storage.has_value()
rusty1s's avatar
rusty1s committed
183

rusty1s's avatar
rusty1s committed
184
185
    def set_value_(self,
                   value: Optional[torch.Tensor],
rusty1s's avatar
rusty1s committed
186
187
                   layout: Optional[str] = None):
        self.storage.set_value_(value, layout)
rusty1s's avatar
rusty1s committed
188
189
        return self

rusty1s's avatar
rusty1s committed
190
191
    def set_value(self,
                  value: Optional[torch.Tensor],
rusty1s's avatar
rusty1s committed
192
193
194
                  layout: Optional[str] = None):
        return self.from_storage(self.storage.set_value(value, layout))

rusty1s's avatar
rusty1s committed
195
    def sparse_sizes(self) -> Tuple[int, int]:
rusty1s's avatar
rusty1s committed
196
        return self.storage.sparse_sizes()
rusty1s's avatar
rusty1s committed
197

rusty1s's avatar
rusty1s committed
198
199
    def sparse_size(self, dim: int) -> int:
        return self.storage.sparse_sizes()[dim]
rusty1s's avatar
rusty1s committed
200

rusty1s's avatar
rusty1s committed
201
    def sparse_resize(self, sparse_sizes: Tuple[int, int]):
rusty1s's avatar
rusty1s committed
202
        return self.from_storage(self.storage.sparse_resize(sparse_sizes))
rusty1s's avatar
rusty1s committed
203

rusty1s's avatar
rusty1s committed
204
    def is_coalesced(self) -> bool:
rusty1s's avatar
rusty1s committed
205
        return self.storage.is_coalesced()
rusty1s's avatar
rusty1s committed
206

rusty1s's avatar
rusty1s committed
207
    def coalesce(self, reduce: str = "sum"):
rusty1s's avatar
rusty1s committed
208
        return self.from_storage(self.storage.coalesce(reduce))
rusty1s's avatar
rusty1s committed
209

rusty1s's avatar
rusty1s committed
210
211
    def fill_cache_(self):
        self.storage.fill_cache_()
rusty1s's avatar
rusty1s committed
212
213
        return self

rusty1s's avatar
rusty1s committed
214
215
    def clear_cache_(self):
        self.storage.clear_cache_()
rusty1s's avatar
rusty1s committed
216
217
218
219
        return self

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

rusty1s's avatar
rusty1s committed
220
221
    def fill_value_(self,
                    fill_value: float,
rusty1s's avatar
rusty1s committed
222
223
                    options: Optional[torch.Tensor] = None):
        if options is not None:
rusty1s's avatar
rusty1s committed
224
225
226
            value = torch.full((self.nnz(), ),
                               fill_value,
                               dtype=options.dtype,
rusty1s's avatar
rusty1s committed
227
228
                               device=self.device())
        else:
rusty1s's avatar
rusty1s committed
229
230
            value = torch.full((self.nnz(), ),
                               fill_value,
rusty1s's avatar
rusty1s committed
231
232
233
                               device=self.device())
        return self.set_value_(value, layout='coo')

rusty1s's avatar
rusty1s committed
234
235
    def fill_value(self,
                   fill_value: float,
rusty1s's avatar
rusty1s committed
236
237
                   options: Optional[torch.Tensor] = None):
        if options is not None:
rusty1s's avatar
rusty1s committed
238
239
240
            value = torch.full((self.nnz(), ),
                               fill_value,
                               dtype=options.dtype,
rusty1s's avatar
rusty1s committed
241
242
                               device=self.device())
        else:
rusty1s's avatar
rusty1s committed
243
244
            value = torch.full((self.nnz(), ),
                               fill_value,
rusty1s's avatar
rusty1s committed
245
246
247
248
                               device=self.device())
        return self.set_value(value, layout='coo')

    def sizes(self) -> List[int]:
rusty1s's avatar
rusty1s committed
249
        sparse_sizes = self.sparse_sizes()
rusty1s's avatar
rusty1s committed
250
251
        value = self.storage.value()
        if value is not None:
rusty1s's avatar
rusty1s committed
252
253
254
            return list(sparse_sizes) + list(value.size())[1:]
        else:
            return list(sparse_sizes)
rusty1s's avatar
rusty1s committed
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270

    def size(self, dim: int) -> int:
        return self.sizes()[dim]

    def dim(self) -> int:
        return len(self.sizes())

    def nnz(self) -> int:
        return self.storage.col().numel()

    def numel(self) -> int:
        value = self.storage.value()
        if value is not None:
            return value.numel()
        else:
            return self.nnz()
rusty1s's avatar
rusty1s committed
271

rusty1s's avatar
rusty1s committed
272
    def density(self) -> float:
rusty1s's avatar
rusty1s committed
273
274
        return self.nnz() / (self.sparse_size(0) * self.sparse_size(1))

rusty1s's avatar
rusty1s committed
275
    def sparsity(self) -> float:
rusty1s's avatar
rusty1s committed
276
277
        return 1 - self.density()

rusty1s's avatar
rusty1s committed
278
    def avg_row_length(self) -> float:
rusty1s's avatar
rusty1s committed
279
280
        return self.nnz() / self.sparse_size(0)

rusty1s's avatar
rusty1s committed
281
    def avg_col_length(self) -> float:
rusty1s's avatar
rusty1s committed
282
283
        return self.nnz() / self.sparse_size(1)

rusty1s's avatar
rusty1s committed
284
    def is_quadratic(self) -> bool:
rusty1s's avatar
rusty1s committed
285
286
        return self.sparse_size(0) == self.sparse_size(1)

rusty1s's avatar
rusty1s committed
287
288
    def is_symmetric(self) -> bool:
        if not self.is_quadratic():
rusty1s's avatar
rusty1s committed
289
290
            return False

rusty1s's avatar
rusty1s committed
291
292
293
294
295
296
        rowptr, col, value1 = self.csr()
        colptr, row, value2 = self.csc()

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

rusty1s's avatar
rusty1s committed
297
        if value1 is None or value2 is None:
rusty1s's avatar
rusty1s committed
298
            return True
rusty1s's avatar
rusty1s committed
299
300
        else:
            return bool((value1 == value2).all())
rusty1s's avatar
rusty1s committed
301

rusty1s's avatar
rusty1s committed
302
303
304
305
306
307
308
309
310
    def to_symmetric(self, reduce: str = "sum"):
        row, col, value = self.coo()

        row, col = torch.cat([row, col], dim=0), torch.cat([col, row], dim=0)
        if value is not None:
            value = torch.cat([value, value], dim=0)

        N = max(self.size(0), self.size(1))

rusty1s's avatar
rusty1s committed
311
312
313
314
315
316
317
        out = SparseTensor(
            row=row,
            rowptr=None,
            col=col,
            value=value,
            sparse_sizes=(N, N),
            is_sorted=False)
rusty1s's avatar
rusty1s committed
318
319
320
        out = out.coalesce(reduce)
        return out

rusty1s's avatar
rusty1s committed
321
    def detach_(self):
rusty1s's avatar
rusty1s committed
322
323
324
        value = self.storage.value()
        if value is not None:
            value.detach_()
rusty1s's avatar
rusty1s committed
325
326
327
        return self

    def detach(self):
rusty1s's avatar
rusty1s committed
328
329
330
331
332
333
334
335
336
337
338
        value = self.storage.value()
        if value is not None:
            value = value.detach()
        return self.set_value(value, layout='coo')

    def requires_grad(self) -> bool:
        value = self.storage.value()
        if value is not None:
            return value.requires_grad
        else:
            return False
rusty1s's avatar
rusty1s committed
339

rusty1s's avatar
rusty1s committed
340
341
    def requires_grad_(self,
                       requires_grad: bool = True,
rusty1s's avatar
rusty1s committed
342
                       options: Optional[torch.Tensor] = None):
rusty1s's avatar
rusty1s committed
343
        if requires_grad and not self.has_value():
rusty1s's avatar
rusty1s committed
344
            self.fill_value_(1., options=options)
rusty1s's avatar
rusty1s committed
345

rusty1s's avatar
rusty1s committed
346
347
348
        value = self.storage.value()
        if value is not None:
            value.requires_grad_(requires_grad)
rusty1s's avatar
rusty1s committed
349
350
        return self

rusty1s's avatar
rusty1s committed
351
    def pin_memory(self):
rusty1s's avatar
rusty1s committed
352
        return self.from_storage(self.storage.pin_memory())
rusty1s's avatar
rusty1s committed
353

rusty1s's avatar
rusty1s committed
354
355
    def is_pinned(self) -> bool:
        return self.storage.is_pinned()
rusty1s's avatar
rusty1s committed
356

rusty1s's avatar
rusty1s committed
357
358
359
360
361
    def options(self) -> torch.Tensor:
        value = self.storage.value()
        if value is not None:
            return value
        else:
rusty1s's avatar
rusty1s committed
362
363
            return torch.tensor(
                0., dtype=torch.float, device=self.storage.col().device)
rusty1s's avatar
rusty1s committed
364
365

    def device(self):
rusty1s's avatar
rusty1s committed
366
        return self.storage.col().device
rusty1s's avatar
rusty1s committed
367
368

    def cpu(self):
rusty1s's avatar
rusty1s committed
369
        return self.device_as(torch.tensor(0.), non_blocking=False)
rusty1s's avatar
rusty1s committed
370

rusty1s's avatar
rusty1s committed
371
372
    def cuda(self,
             options: Optional[torch.Tensor] = None,
rusty1s's avatar
rusty1s committed
373
             non_blocking: bool = False):
rusty1s's avatar
rusty1s committed
374
375
        if options is not None:
            return self.device_as(options, non_blocking)
rusty1s's avatar
rusty1s committed
376
        else:
rusty1s's avatar
rusty1s committed
377
378
            options = torch.tensor(0.).cuda()
            return self.device_as(options, non_blocking)
rusty1s's avatar
rusty1s committed
379

rusty1s's avatar
rusty1s committed
380
381
    def is_cuda(self) -> bool:
        return self.storage.col().is_cuda
rusty1s's avatar
rusty1s committed
382

rusty1s's avatar
rusty1s committed
383
384
    def dtype(self):
        return self.options().dtype
rusty1s's avatar
rusty1s committed
385

rusty1s's avatar
rusty1s committed
386
387
    def is_floating_point(self) -> bool:
        return torch.is_floating_point(self.options())
rusty1s's avatar
rusty1s committed
388
389

    def bfloat16(self):
rusty1s's avatar
rusty1s committed
390
391
        return self.type_as(
            torch.tensor(0, dtype=torch.bfloat16, device=self.device()))
rusty1s's avatar
rusty1s committed
392
393

    def bool(self):
rusty1s's avatar
rusty1s committed
394
395
        return self.type_as(
            torch.tensor(0, dtype=torch.bool, device=self.device()))
rusty1s's avatar
rusty1s committed
396
397

    def byte(self):
rusty1s's avatar
rusty1s committed
398
399
        return self.type_as(
            torch.tensor(0, dtype=torch.uint8, device=self.device()))
rusty1s's avatar
rusty1s committed
400
401

    def char(self):
rusty1s's avatar
rusty1s committed
402
403
        return self.type_as(
            torch.tensor(0, dtype=torch.int8, device=self.device()))
rusty1s's avatar
rusty1s committed
404
405

    def half(self):
rusty1s's avatar
rusty1s committed
406
407
        return self.type_as(
            torch.tensor(0, dtype=torch.half, device=self.device()))
rusty1s's avatar
rusty1s committed
408
409

    def float(self):
rusty1s's avatar
rusty1s committed
410
411
        return self.type_as(
            torch.tensor(0, dtype=torch.float, device=self.device()))
rusty1s's avatar
rusty1s committed
412
413

    def double(self):
rusty1s's avatar
rusty1s committed
414
415
        return self.type_as(
            torch.tensor(0, dtype=torch.double, device=self.device()))
rusty1s's avatar
rusty1s committed
416
417

    def short(self):
rusty1s's avatar
rusty1s committed
418
419
        return self.type_as(
            torch.tensor(0, dtype=torch.short, device=self.device()))
rusty1s's avatar
rusty1s committed
420
421

    def int(self):
rusty1s's avatar
rusty1s committed
422
423
        return self.type_as(
            torch.tensor(0, dtype=torch.int, device=self.device()))
rusty1s's avatar
rusty1s committed
424
425

    def long(self):
rusty1s's avatar
rusty1s committed
426
427
        return self.type_as(
            torch.tensor(0, dtype=torch.long, device=self.device()))
rusty1s's avatar
rusty1s committed
428
429
430

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

rusty1s's avatar
rusty1s committed
431
    def to_dense(self, options: Optional[torch.Tensor] = None):
rusty1s's avatar
rusty1s committed
432
        row, col, value = self.coo()
rusty1s's avatar
rusty1s committed
433

rusty1s's avatar
fixes  
rusty1s committed
434
        if value is not None:
rusty1s's avatar
rusty1s committed
435
436
            mat = torch.zeros(
                self.sizes(), dtype=value.dtype, device=self.device())
rusty1s's avatar
fixes  
rusty1s committed
437
        elif options is not None:
rusty1s's avatar
rusty1s committed
438
439
            mat = torch.zeros(
                self.sizes(), dtype=options.dtype, device=self.device())
rusty1s's avatar
rusty1s committed
440
441
442
443
444
445
        else:
            mat = torch.zeros(self.sizes(), device=self.device())

        if value is not None:
            mat[row, col] = value
        else:
rusty1s's avatar
rusty1s committed
446
447
            mat[row, col] = torch.ones(
                self.nnz(), dtype=mat.dtype, device=mat.device)
rusty1s's avatar
rusty1s committed
448

rusty1s's avatar
rusty1s committed
449
450
        return mat

rusty1s's avatar
rusty1s committed
451
452
    def to_torch_sparse_coo_tensor(self,
                                   options: Optional[torch.Tensor] = None):
rusty1s's avatar
rusty1s committed
453
454
455
        row, col, value = self.coo()
        index = torch.stack([row, col], dim=0)
        if value is None:
rusty1s's avatar
rusty1s committed
456
            if options is not None:
rusty1s's avatar
rusty1s committed
457
458
                value = torch.ones(
                    self.nnz(), dtype=options.dtype, device=self.device())
rusty1s's avatar
rusty1s committed
459
            else:
rusty1s's avatar
rusty1s committed
460
                value = torch.ones(self.nnz(), device=self.device())
rusty1s's avatar
rusty1s committed
461

rusty1s's avatar
rusty1s committed
462
        return torch.sparse_coo_tensor(index, value, self.sizes())
rusty1s's avatar
rusty1s committed
463

rusty1s's avatar
rusty1s committed
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478

# Python Bindings #############################################################

Dtype = Optional[torch.dtype]
Device = Optional[Union[torch.device, str]]


def share_memory_(self: SparseTensor) -> SparseTensor:
    self.storage.share_memory_()


def is_shared(self: SparseTensor) -> bool:
    return self.storage.is_shared()


rusty1s's avatar
typing  
rusty1s committed
479
480
481
def to(self, *args: Optional[List[Any]],
       **kwargs: Optional[Dict[str, Any]]) -> SparseTensor:

rusty1s's avatar
rusty1s committed
482
    device, dtype, non_blocking = torch._C._nn._parse_to(*args, **kwargs)
rusty1s's avatar
rusty1s committed
483
484
485
486
487
488
489
490
491

    if dtype is not None:
        self = self.type_as(torch.tensor(0., dtype=dtype))
    if device is not None:
        self = self.device_as(torch.tensor(0., device=device), non_blocking)

    return self


rusty1s's avatar
typing  
rusty1s committed
492
def __getitem__(self: SparseTensor, index: Any) -> SparseTensor:
rusty1s's avatar
repr  
rusty1s committed
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
    index = list(index) if isinstance(index, tuple) else [index]
    # More than one `Ellipsis` is not allowed...
    if len([i for i in index if not torch.is_tensor(i) and i == ...]) > 1:
        raise SyntaxError

    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:
                raise SyntaxError
            dim = self.dim() - len(index)
        else:
            raise SyntaxError

    return out


rusty1s's avatar
typing  
rusty1s committed
534
def __repr__(self: SparseTensor) -> str:
rusty1s's avatar
repr  
rusty1s committed
535
536
537
    i = ' ' * 6
    row, col, value = self.coo()
    infos = []
rusty1s's avatar
rusty1s committed
538
539
    infos += [f'row={indent(row.__repr__(), i)[len(i):]}']
    infos += [f'col={indent(col.__repr__(), i)[len(i):]}']
rusty1s's avatar
repr  
rusty1s committed
540
541

    if value is not None:
rusty1s's avatar
rusty1s committed
542
        infos += [f'val={indent(value.__repr__(), i)[len(i):]}']
rusty1s's avatar
repr  
rusty1s committed
543
544

    infos += [
rusty1s's avatar
rusty1s committed
545
546
        f'size={tuple(self.sizes())}, nnz={self.nnz()}, '
        f'density={100 * self.density():.02f}%'
rusty1s's avatar
repr  
rusty1s committed
547
    ]
rusty1s's avatar
rusty1s committed
548

rusty1s's avatar
repr  
rusty1s committed
549
550
551
    infos = ',\n'.join(infos)

    i = ' ' * (len(self.__class__.__name__) + 1)
rusty1s's avatar
rusty1s committed
552
    return f'{self.__class__.__name__}({indent(infos, i)[len(i):]})'
rusty1s's avatar
repr  
rusty1s committed
553
554


rusty1s's avatar
rusty1s committed
555
556
557
SparseTensor.share_memory_ = share_memory_
SparseTensor.is_shared = is_shared
SparseTensor.to = to
rusty1s's avatar
repr  
rusty1s committed
558
559
SparseTensor.__getitem__ = __getitem__
SparseTensor.__repr__ = __repr__
rusty1s's avatar
rusty1s committed
560
561
562

# Scipy Conversions ###########################################################

rusty1s's avatar
rusty1s committed
563
564
ScipySparseMatrix = Union[scipy.sparse.coo_matrix, scipy.sparse.
                          csr_matrix, scipy.sparse.csc_matrix]
rusty1s's avatar
rusty1s committed
565
566
567


@torch.jit.ignore
rusty1s's avatar
rusty1s committed
568
def from_scipy(mat: ScipySparseMatrix, has_value: bool = True) -> SparseTensor:
rusty1s's avatar
rusty1s committed
569
570
571
572
573
574
575
576
577
    colptr = None
    if isinstance(mat, scipy.sparse.csc_matrix):
        colptr = torch.from_numpy(mat.indptr).to(torch.long)

    mat = mat.tocsr()
    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)
rusty1s's avatar
rusty1s committed
578
579
580
    value = None
    if has_value:
        value = torch.from_numpy(mat.data)
rusty1s's avatar
rusty1s committed
581
582
    sparse_sizes = mat.shape[:2]

rusty1s's avatar
rusty1s committed
583
584
585
586
587
588
589
590
591
592
593
594
    storage = SparseStorage(
        row=row,
        rowptr=rowptr,
        col=col,
        value=value,
        sparse_sizes=sparse_sizes,
        rowcount=None,
        colptr=colptr,
        colcount=None,
        csr2csc=None,
        csc2csr=None,
        is_sorted=True)
rusty1s's avatar
rusty1s committed
595
596
597
598
599

    return SparseTensor.from_storage(storage)


@torch.jit.ignore
rusty1s's avatar
rusty1s committed
600
601
def to_scipy(self: SparseTensor,
             layout: Optional[str] = None,
rusty1s's avatar
rusty1s committed
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
             dtype: Optional[torch.dtype] = None) -> ScipySparseMatrix:
    assert self.dim() == 2
    layout = get_layout(layout)

    if not self.has_value():
        ones = torch.ones(self.nnz(), dtype=dtype).numpy()

    if layout == 'coo':
        row, col, value = self.coo()
        row = row.detach().cpu().numpy()
        col = col.detach().cpu().numpy()
        value = value.detach().cpu().numpy() if self.has_value() else ones
        return scipy.sparse.coo_matrix((value, (row, col)), self.sizes())
    elif layout == 'csr':
        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
        return scipy.sparse.csr_matrix((value, col, rowptr), self.sizes())
    elif layout == 'csc':
        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
        return scipy.sparse.csc_matrix((value, row, colptr), self.sizes())


SparseTensor.from_scipy = from_scipy
SparseTensor.to_scipy = to_scipy

# Hacky fixes #################################################################

rusty1s's avatar
rusty1s committed
634
# Fix standard operators of `torch.Tensor` for PyTorch<=1.3.
rusty1s's avatar
rusty1s committed
635
# https://github.com/pytorch/pytorch/pull/31769
rusty1s's avatar
rusty1s committed
636
637
TORCH_MAJOR = int(torch.__version__.split('.')[0])
TORCH_MINOR = int(torch.__version__.split('.')[1])
rusty1s's avatar
rusty1s committed
638
if (TORCH_MAJOR < 1) or (TORCH_MAJOR == 1 and TORCH_MINOR <= 3):
rusty1s's avatar
rusty1s committed
639
640

    def add(self, other):
rusty1s's avatar
rusty1s committed
641
642
643
        if torch.is_tensor(other) or is_scalar(other):
            return self.add(other)
        return NotImplemented
rusty1s's avatar
rusty1s committed
644
645

    def mul(self, other):
rusty1s's avatar
rusty1s committed
646
647
648
        if torch.is_tensor(other) or is_scalar(other):
            return self.mul(other)
        return NotImplemented
rusty1s's avatar
rusty1s committed
649
650

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