forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_sparse_csr.py
3098 lines (2654 loc) · 150 KB
/
test_sparse_csr.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Owner(s): ["module: sparse"]
import torch
import random
import itertools
import unittest
import functools
from torch.testing import make_tensor
from torch.testing._internal.common_cuda import SM53OrLater, SM80OrLater, TEST_CUSPARSE_GENERIC
from torch.testing._internal.common_utils import \
(TEST_WITH_ROCM, TEST_SCIPY, TEST_NUMPY, TEST_MKL, IS_WINDOWS, TestCase, run_tests, load_tests, coalescedonoff, parametrize,
subtest)
from torch.testing._internal.common_device_type import \
(ops, instantiate_device_type_tests, dtypes, OpDTypes, dtypesIfCUDA, onlyCPU, onlyCUDA, skipCUDAIfNoSparseGeneric,
precisionOverride, skipMeta, skipCUDAIf, skipCUDAIfRocm, skipCPUIfNoMklSparse, skipCUDAIfRocmVersionLessThan)
from torch.testing._internal.common_methods_invocations import \
(op_db, sparse_csr_unary_ufuncs, ReductionOpInfo)
from torch.testing._internal.common_cuda import _get_torch_cuda_version, CUDA11OrLater, TEST_CUDA
from torch.testing._internal.common_dtype import (
floating_types, all_types_and_complex_and, floating_and_complex_types, floating_types_and,
all_types_and_complex, floating_and_complex_types_and
)
from test_sparse import CUSPARSE_SPMM_COMPLEX128_SUPPORTED
if TEST_SCIPY:
import scipy.sparse as sp
if TEST_NUMPY:
import numpy as np
# load_tests from torch.testing._internal.common_utils is used to automatically filter tests for
# sharding on sandcastle. This line silences flake warnings
load_tests = load_tests
no_mkl_sparse = IS_WINDOWS or not TEST_MKL
def _check_cusparse_triangular_solve_available():
version = _get_torch_cuda_version()
# cusparseSpSM was added in 11.3.1 but we don't have access to patch version
min_supported_version = (11, 4)
return version >= min_supported_version
def _check_cusparse_spgemm_available():
# cusparseSpGEMM was added in 11.0
version = _get_torch_cuda_version()
min_supported_version = (11, 0)
return version >= min_supported_version
def _check_cusparse_sddmm_available():
version = _get_torch_cuda_version()
# cusparseSDDMM was added in 11.2.1 but we don't have access to patch version
min_supported_version = (11, 3)
return version >= min_supported_version
_sparse_csr_ops = list(filter(lambda op: op.supports_sparse_csr, op_db))
_sparse_compressed_ops = list(filter(lambda op: (op.supports_sparse_csr or op.supports_sparse_csc
or op.supports_sparse_bsr or op.supports_sparse_bsc), op_db))
binary_functions_with_dense_output = ['mm', 'mv', ]
binary_ops_with_dense_output = list(filter(lambda op: op.name in binary_functions_with_dense_output, op_db))
UNARY_EWISE_CSR_ALLOW_AUTOGRAD = [
'abs',
'conj_physical',
'deg2rad',
'neg',
'positive',
'frac',
'nn.functional.relu',
'log1p',
'rad2deg'
]
# This should be just an import from test_linalg instead of code duplication
# but https://github.com/pytorch/pytorch/pull/63511#discussion_r733989701
def _test_addmm_addmv(
test_case,
f,
t,
m,
v,
*,
alpha=None,
beta=None,
transpose_out=False,
layout=torch.strided,
mode=None
):
"""
Unified test for checking `f(t, m, v, alpha=alpha, beta=beta)` computation,
where f is `torch.addmv` or `torch.addmm`.
`transpose_out` controls whether the out argument is in column-major order.
`layout` controls whether `m` is converted to specified layout or not.
Custom behaviour is implemented only for torch.sparse_csr layout.
"""
dtype = t.dtype
numpy_dtype = dtype
if dtype in {torch.bfloat16}:
numpy_dtype = torch.float
if dtype.is_complex:
alpha = 0.9 + 0.3j if alpha is None else alpha
beta = 0.5 + 0.6j if beta is None else beta
else:
alpha = 1.2 if alpha is None else alpha
beta = 0.8 if beta is None else beta
def convert_layout(mat):
if layout == torch.sparse_csr:
return mat.to_sparse_csr()
elif layout == torch.sparse_csc:
return mat.to_sparse_csc()
else:
assert mat.layout == layout
return mat
if mode == "all_sparse":
res1 = f(*map(convert_layout, (t, m, v)), alpha=alpha, beta=beta)
test_case.assertEqual(res1.layout, layout)
res1 = res1.to_dense()
elif mode == "dense_result":
res1 = f(t, convert_layout(m), convert_layout(v), alpha=alpha, beta=beta)
else:
res1 = f(t, convert_layout(m), v, alpha=alpha, beta=beta)
res2 = torch.full_like(res1, float('nan'))
if transpose_out:
res2 = res2.t().clone(memory_format=torch.contiguous_format).t()
f(t, convert_layout(m), v, alpha=alpha, beta=beta, out=res2)
res3 = alpha * (m.to(numpy_dtype).cpu().numpy() @ v.to(numpy_dtype).cpu().numpy())
if beta != 0:
res3 += (beta * t).to(numpy_dtype).cpu().numpy()
res3 = torch.from_numpy(res3).to(dtype)
test_case.assertEqual(res1, res2)
test_case.assertEqual(res1, res3)
class TestSparseCSRSampler(TestCase):
def test_make_crow_indices(self):
# Here we test the correctness of the crow_indices algorithm
# and testing it on CPU and with int32 dtype will be
# sufficient.
device = torch.device('cpu')
index_dtype = torch.int32
for n_rows in range(1, 10):
for n_cols in range(1, 10):
for nnz in range(0, n_rows * n_cols + 1):
crow_indices = self._make_crow_indices(
n_rows, n_cols, nnz,
device=device, dtype=index_dtype)
self.assertEqual(len(crow_indices), n_rows + 1)
counts = crow_indices[1:] - crow_indices[:-1]
self.assertEqual(counts.sum(), nnz)
self.assertGreaterEqual(counts.min(), 0)
self.assertLessEqual(counts.max(), n_cols)
def all_sparse_compressed_layouts(test_name='layout'):
return parametrize(test_name, [
subtest(torch.sparse_csr, name='SparseCSR'),
subtest(torch.sparse_csc, name='SparseCSC'),
subtest(torch.sparse_bsr, name='SparseBSR'),
subtest(torch.sparse_bsc, name='SparseBSC')])
def sparse_compressed_nonblock_layouts(test_name='layout'):
return parametrize(test_name, [
subtest(torch.sparse_csr, name='SparseCSR'),
subtest(torch.sparse_csc, name='SparseCSC')])
sparse_compressed_indices_methods = {
torch.sparse_csr: (torch.Tensor.crow_indices, torch.Tensor.col_indices),
torch.sparse_csc: (torch.Tensor.ccol_indices, torch.Tensor.row_indices),
torch.sparse_bsr: (torch.Tensor.crow_indices, torch.Tensor.col_indices),
torch.sparse_bsc: (torch.Tensor.ccol_indices, torch.Tensor.row_indices),
}
def batched_nonbatched(test_name='batched'):
return parametrize(test_name, [
subtest(True, name="Batched"),
subtest(False, name="NonBatched")
])
def hybrid_nonhybrid(test_name='hybrid'):
return parametrize(test_name, [
subtest(True, name="Hybrid"),
subtest(False, name="NonHybrid")
])
class TestSparseCompressed(TestCase):
"""Testing sparse compressed (CSR, CSC, BSR, BSC) tensor generic features.
"""
def genTensor(self, size, nnz, *, layout, device=None, dtype=torch.float, index_dtype=torch.int64):
if device is None:
device = self.device_type
return self.genSparseCompressedTensor(size, nnz, device=device, dtype=dtype, index_dtype=index_dtype, layout=layout)
@all_sparse_compressed_layouts()
@onlyCPU
def test_layout(self, layout):
self.assertIn(str(layout), {'torch.sparse_csr', 'torch.sparse_csc', 'torch.sparse_bsr', 'torch.sparse_bsc'})
self.assertEqual(type(layout), torch.layout)
@parametrize('shape_and_device_inference', [subtest(False, name='_'), subtest(True, name='shape_and_device_inference')])
@parametrize('use_factory_function', [subtest(False, name='_'), subtest(True, name='factory')])
@parametrize('input_kind', [subtest('tensor', name='from_tensor'), subtest('list', name='from_list')])
@all_sparse_compressed_layouts()
@dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))
def test_sparse_compressed_constructor(self, layout, device, dtype,
use_factory_function, shape_and_device_inference, input_kind):
if input_kind == 'list' and shape_and_device_inference:
if torch.device(device).type == 'cuda':
# list inputs to factory/constructor function without
# specifying device will result a sparse compressed tensor
# on CPU. So, skip testing against cuda device as unused.
self.skipTest("nothing to test")
if dtype not in {torch.float32, torch.complex64, torch.int64, torch.bool}:
self.skipTest("dtype not supported with list values")
expected_devices = [torch.device(device)]
if TEST_CUDA and torch.device(device).type == 'cuda' and torch.cuda.device_count() >= 2 and not shape_and_device_inference:
expected_devices.append(torch.device('cuda:1'))
factory_function = {
torch.sparse_csr: torch.sparse_csr_tensor,
torch.sparse_csc: torch.sparse_csc_tensor,
torch.sparse_bsr: torch.sparse_bsr_tensor,
torch.sparse_bsc: torch.sparse_bsc_tensor,
}[layout]
compressed_indices_mth, plain_indices_mth = sparse_compressed_indices_methods[layout]
if input_kind == 'list':
index_dtypes = [torch.int64]
else:
index_dtypes = [torch.int32, torch.int64]
for index_dtype in index_dtypes:
for expected_device in expected_devices:
for (compressed_indices, plain_indices, values), kwargs in self.generate_simple_inputs(
layout, device=expected_device, dtype=dtype, index_dtype=index_dtype,
# skip zero-sized tensors for list inputs:
enable_zero_sized=input_kind != 'list',
output_tensor=False):
size = kwargs['size']
if shape_and_device_inference and 0 in size:
# skip shape inference for zero-sized tensor
# inputs because (i) the shape determined from
# an empty list is ambiguous, and (ii) the
# size of the plain dimension defined as
# max(plain_indices) is undefined if
# plain_indices has no values
continue
compressed_indices_expect = compressed_indices
plain_indices_expect = plain_indices
values_expect = values
if input_kind == 'list':
compressed_indices = compressed_indices.tolist()
plain_indices = plain_indices.tolist()
values = values.tolist()
if use_factory_function:
if shape_and_device_inference:
sparse = factory_function(compressed_indices, plain_indices, values)
else:
sparse = factory_function(compressed_indices, plain_indices, values, size,
dtype=dtype, device=expected_device)
else:
if shape_and_device_inference:
sparse = torch.sparse_compressed_tensor(compressed_indices, plain_indices, values, layout=layout)
else:
sparse = torch.sparse_compressed_tensor(compressed_indices, plain_indices, values, size,
dtype=dtype, layout=layout, device=expected_device)
self.assertEqual(layout, sparse.layout)
self.assertEqual(size, sparse.shape)
self.assertEqual(compressed_indices_expect, compressed_indices_mth(sparse))
self.assertEqual(plain_indices_expect, plain_indices_mth(sparse))
self.assertEqual(values_expect, sparse.values())
self.assertEqual(sparse.device, sparse.values().device)
self.assertEqual(sparse.device, expected_device)
@skipMeta
@sparse_compressed_nonblock_layouts()
@dtypes(*all_types_and_complex_and(torch.bool, torch.bfloat16, torch.half))
def test_empty(self, layout, device, dtype):
ns = [5, 2, 0]
batch_shapes = [(), (2,), (2, 3)]
compressed_dim = {
torch.sparse_csr: -2,
torch.sparse_csc: -1,
}[layout]
compressed_indices_mth, plain_indices_mth = sparse_compressed_indices_methods[layout]
for m, n, b in itertools.product(ns, ns, batch_shapes):
shape = (*b, m, n)
result = torch.empty(shape, dtype=dtype, device=device, layout=layout)
self.assertEqual(result.shape, shape)
self.assertEqual(result.dtype, dtype)
self.assertEqual(result.device, torch.device(device))
self.assertEqual(result.layout, layout)
self.assertEqual(compressed_indices_mth(result).shape, (*b, shape[compressed_dim] + 1,))
self.assertEqual(plain_indices_mth(result).shape, (*b, 0,))
self.assertEqual(result.values().shape, (*b, 0,))
self.assertEqual(result._nnz(), 0)
self.assertEqual(compressed_indices_mth(result).device, torch.device(device))
self.assertEqual(plain_indices_mth(result).device, torch.device(device))
self.assertEqual(result.values().device, torch.device(device))
self.assertEqual(compressed_indices_mth(result).dtype, torch.int64)
self.assertEqual(plain_indices_mth(result).dtype, torch.int64)
self.assertEqual(result.values().dtype, dtype)
@skipMeta
@sparse_compressed_nonblock_layouts()
@dtypes(*all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16))
def test_empty_errors(self, layout, device, dtype):
with self.assertRaisesRegex(RuntimeError,
"torch.empty: Only batched sparse compressed \\(non-block\\) tensors are supported"
", but got size"):
torch.empty((5,), dtype=dtype, device=device, layout=layout)
@skipMeta
@all_sparse_compressed_layouts()
@dtypes(*all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16))
def test_clone(self, layout, device, dtype):
for sparse in self.generate_simple_inputs(
layout, device=device, dtype=dtype, index_dtype=torch.int32):
cloned_sparse = sparse.clone()
self.assertEqual(sparse, cloned_sparse)
@all_sparse_compressed_layouts()
def test_print(self, layout, device):
compressed_indices_mth, plain_indices_mth = sparse_compressed_indices_methods[layout]
printed = []
for enable_hybrid in [False, True]:
# using local patterns for test_print stability
patterns = [
# 2 x 3 batch of 3 x 2 tensors, trivial blocksize, non-hybrid/hybrid:
([[[[1, 2, 0],
[1, 0, 3]],
[[1, 2, 3],
[1, 0, 0]],
[[1, 0, 0],
[1, 2, 3]]],
[[[0, 2, 0],
[1, 2, 3]],
[[1, 0, 3],
[1, 2, 0]],
[[1, 2, 3],
[0, 2, 0]]]], [(2, 1)], [(), (4,)] if enable_hybrid else [()]),
# tensor with non-trivial blocksize, non-hybrid/hybrid:
([[0, 1, 0, 2, 0, 2],
[0, 1, 0, 0, 2, 0],
[3, 3, 3, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 5, 0, 6, 6, 6],
[5, 0, 5, 6, 6, 6],
[0, 0, 0, 0, 8, 8],
[7, 7, 7, 0, 8, 8]], [(2, 3)], [(), (4, 2)] if enable_hybrid else [()]),
]
for index_dtype in [torch.int32, torch.int64]:
for dtype in [torch.float32, torch.float64]:
for (compressed_indices, plain_indices, values), kwargs in self.generate_simple_inputs(
layout, device=device, dtype=dtype, index_dtype=index_dtype, enable_hybrid=enable_hybrid,
enable_zero_sized=False, output_tensor=False, patterns=patterns):
size = tuple(kwargs['size'])
block_ndim = 2 if layout in {torch.sparse_bsr, torch.sparse_bsc} else 0
base_ndim = 2
batch_ndim = compressed_indices.dim() - 1
dense_ndim = values.dim() - batch_ndim - block_ndim - 1
if enable_hybrid and dense_ndim == 0:
# non-hybrid cases are covered by the enable_hybrid==False loop
continue
batchsize = size[:batch_ndim]
basesize = size[batch_ndim:batch_ndim + base_ndim]
densesize = size[batch_ndim + base_ndim:]
assert len(densesize) == dense_ndim
printed.append("########## {}/{}/size={}+{}+{} ##########".format(
dtype, index_dtype, batchsize, basesize, densesize))
x = torch.sparse_compressed_tensor(compressed_indices,
plain_indices,
values, size, dtype=dtype, layout=layout, device=device)
printed.append("# sparse tensor")
printed.append(str(x))
printed.append(f"# _{compressed_indices_mth.__name__}")
printed.append(str(compressed_indices_mth(x)))
printed.append(f"# _{plain_indices_mth.__name__}")
printed.append(str(plain_indices_mth(x)))
printed.append("# _values")
printed.append(str(x.values()))
printed.append('')
printed.append('')
orig_maxDiff = self.maxDiff
self.maxDiff = None
try:
self.assertExpected('\n'.join(printed))
self.maxDiff = orig_maxDiff
except Exception:
self.maxDiff = orig_maxDiff
raise
@skipMeta
@all_sparse_compressed_layouts()
@dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))
def test_copy(self, layout, device, dtype):
def run_test(shape, blocksize, nnz, index_type):
a = self.genSparseCompressedTensor(shape, nnz, dtype=dtype, layout=layout, device=device,
index_dtype=index_dtype, blocksize=blocksize)
b = self.genSparseCompressedTensor(shape, nnz, dtype=dtype, layout=layout, device=device,
index_dtype=index_dtype, blocksize=blocksize)
a.copy_(b)
self.assertEqual(a, b)
ns = [(9, 3), (2, 1), (0, 0)] # (number of dimensions, the corresponding block size)
batch_shapes = [(), (2,), (2, 3)]
for ((m, bm), (n, bn), b), index_dtype in zip(itertools.product(ns, ns, batch_shapes), [torch.int32, torch.int64]):
blocksize = (bm, bn) if layout in {torch.sparse_bsr, torch.sparse_bsc} else ()
run_test((*b, m, n), blocksize, 0, index_dtype)
run_test((*b, m, n), blocksize, m * n, index_dtype)
@skipMeta
@all_sparse_compressed_layouts()
@dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))
def test_copy_errors(self, layout, device, dtype):
blocksize = (2, 3) if layout in {torch.sparse_bsr, torch.sparse_bsc} else ()
nnz = 6 if layout in {torch.sparse_bsr, torch.sparse_bsc} else 1
shape1 = (2 * 6, 3 * 6) if layout in {torch.sparse_bsr, torch.sparse_bsc} else (2, 3)
for index_dtype in [torch.int32, torch.int64]:
a = self.genSparseCompressedTensor(shape1, 0, dtype=dtype, layout=layout, device=device,
index_dtype=index_dtype, blocksize=blocksize)
with self.assertRaisesRegex(RuntimeError,
"copy of sparse compressed tensors having different layouts is not supported."):
a.copy_(torch.empty(a.shape, dtype=dtype, device=device))
b = self.genSparseCompressedTensor(shape1, nnz, dtype=dtype, layout=layout, device=device,
index_dtype=index_dtype, blocksize=blocksize)
assert a._nnz() != b._nnz(), (a._nnz(), b._nnz())
with self.assertRaisesRegex(RuntimeError,
"only sparse compressed tensors with the same number of specified elements are supported."):
a.copy_(b)
shape2 = tuple(reversed(shape1))
c = self.genSparseCompressedTensor(shape2, nnz, dtype=dtype, layout=layout, device=device,
index_dtype=index_dtype, blocksize=blocksize)
with self.assertRaisesRegex(
RuntimeError,
"expected shapes of self and src to match along dimension"):
b.copy_(c)
if blocksize:
blocksize1 = tuple(reversed(blocksize))
d = self.genSparseCompressedTensor(shape1, nnz, dtype=dtype, layout=layout, device=device,
index_dtype=index_dtype, blocksize=blocksize1)
with self.assertRaisesRegex(RuntimeError,
"copy of sparse compressed tensors having different block sizes is not supported"):
b.copy_(d)
def _smallest_divisor(self, n):
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return i
return n
@all_sparse_compressed_layouts()
@ops(_sparse_compressed_ops)
def test_consistency(self, layout, device, dtype, op):
# TODO: Normaly, we should use DecorateInfo instead of
# skipTest but this requires implemening OpInfo support for
# layout as a test parameter (similar to device and dtype).
if not (layout == torch.sparse_csr and op.supports_sparse_csr
or layout == torch.sparse_csc and op.supports_sparse_csc
or layout == torch.sparse_bsr and op.supports_sparse_bsr
or layout == torch.sparse_bsc and op.supports_sparse_bsc):
self.skipTest(f"{op.name} does not support input with {layout} layout")
# FIXME: remove in followup once integer support is landed for segment_reduce
if (layout == torch.sparse_csr and not dtype.is_floating_point
and op.name in ('masked.mean', 'masked.amax', 'masked.amin')):
self.skipTest(f"{op.name} does not support input with {layout} layout")
require_mask = isinstance(op, ReductionOpInfo) and 'masked.' in op.name
if require_mask and layout in {torch.sparse_bsr, torch.sparse_bsc}:
self.skipTest(f"{op.name} does not support input with {layout} layout")
samples = list(op.sample_inputs(device, dtype))
# Fail early to prevent silent success with this test
ndims_equals_2d = (s.input.ndim == 2 for s in samples)
if not any(ndims_equals_2d):
raise ValueError("Expected at least one 2D tensor in samples.")
count = 0
for sample in samples:
assert torch.is_tensor(sample.input)
# Sparse CSR/CSC only supports 2D tensors as inputs
if sample.input.ndim != 2:
continue
if isinstance(op, ReductionOpInfo):
# Reductions on sparse compressed require keepdim=True
if not sample.kwargs.get('keepdim'):
continue
# Reductions on sparse compressed tensors require explicit mask
if require_mask and sample.kwargs.get('mask') is None:
continue
expected = op(sample.input, **sample.kwargs)
assert torch.is_tensor(expected)
# Use smallest non-trivial blocksize for the given input shape:
blocksize = tuple(map(self._smallest_divisor, sample.input.shape[-2:]))
if layout is torch.sparse_bsr:
sparse = sample.input.to_sparse_bsr(blocksize)
elif layout is torch.sparse_bsc:
sparse = sample.input.to_sparse_bsc(blocksize)
elif layout is torch.sparse_csr:
sparse = sample.input.to_sparse_csr()
elif layout is torch.sparse_csc:
sparse = sample.input.to_sparse_csc()
else:
assert 0, layout
assert torch.is_tensor(sparse)
output = op(sparse, **sample.kwargs)
assert torch.is_tensor(output)
strided_output = output.to_dense()
if require_mask:
output_mask = torch.masked._output_mask(op.op, sample.input, **sample.kwargs)
expected.masked_fill_(~output_mask, 0)
self.assertEqual(strided_output, expected)
count += 1
# Better fail late to prevent silent success with this test
if not count:
raise ValueError("Expected at least one sample with keepdim and/or explicit mask for reductions.")
@skipMeta
@all_sparse_compressed_layouts()
@all_sparse_compressed_layouts('layout2')
@dtypes(*all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16))
def test_empty_like(self, layout, layout2, device, dtype):
for sparse in self.generate_simple_inputs(layout):
if layout == layout2:
result = torch.empty_like(sparse, layout=layout2)
compressed_indices_mth, plain_indices_mth = sparse_compressed_indices_methods[result.layout]
torch._validate_sparse_compressed_tensor_args(compressed_indices_mth(result),
plain_indices_mth(result),
result.values(),
result.shape,
result.layout)
self.assertEqual(sparse.shape, result.shape)
else:
self.assertRaisesRegex(
RuntimeError,
"empty_like with different sparse layout is not supported",
lambda: torch.empty_like(sparse, layout=layout2)
)
@skipMeta
@all_sparse_compressed_layouts()
@dtypes(*all_types_and_complex_and(torch.half, torch.bool, torch.bfloat16))
def test_validate(self, layout, device, dtype):
for index_dtype in [torch.int32, torch.int64]:
for (compressed_indices, plain_indices, values), kwargs in self.generate_simple_inputs(
layout, device=device, dtype=dtype, index_dtype=index_dtype, output_tensor=False):
size = kwargs['size']
torch._validate_sparse_compressed_tensor_args(compressed_indices, plain_indices, values, size, layout)
def _generate_invalid_input(self, layout, device):
from functools import partial
def shape(shape, basedim=0):
blocksize = (1, 1)
if layout is torch.sparse_csc:
shape = shape[:basedim] + (shape[basedim + 1], shape[basedim]) + shape[basedim + 2:]
elif layout is torch.sparse_bsc:
shape = shape[:basedim] + (shape[basedim + 1] * blocksize[1], shape[basedim] * blocksize[0]) + shape[basedim + 2:]
elif layout is torch.sparse_bsr:
shape = shape[:basedim] + (shape[basedim] * blocksize[0], shape[basedim + 1] * blocksize[1]) + shape[basedim + 2:]
return shape
def values(lst, device=device):
if layout in {torch.sparse_bsr, torch.sparse_bsc}:
lst = [[[item]] for item in lst]
return torch.tensor(lst, device=device)
tensor = partial(torch.tensor, device=device)
values = partial(values, device=device)
yield ('incontiguous compressed_indices',
tensor([0, -1, 2, -1, 4, -1])[::2],
tensor([0, 1, 0, 2]),
values([1, 2, 3, 4]),
shape((2, 3)),
'expected compressed_indices to be a strided and contiguous tensor')
yield ('incontiguous plain_indices',
tensor([0, 2, 4]),
tensor([0, -1, 1, -1, 0, -1, 2, -1])[::2],
values([1, 2, 3, 4]),
shape((2, 3)),
'expected plain_indices to be a strided and contiguous tensor')
yield ('incontiguous values',
tensor([0, 2, 4]),
tensor([0, 1, 0, 2]),
values([1, 1, 2, 2, 3, 3, 4, 4])[::2],
shape((2, 3)),
'expected values to be a strided and contiguous tensor')
yield ('0-D compressed_indices',
tensor(0),
tensor([0, 1, 0, 2]),
values([1, 2, 3, 4]),
shape((2, 3)),
'compressed_indices must have dimensionality >= 1 but got 0')
yield ('compressed/plain_indices mismatch of dimensionalities',
tensor([[0, 2, 4]]),
tensor([0, 1, 0, 2]),
values([1, 2, 3, 4]),
shape((2, 3)),
'compressed_indices and plain_indices dimensionalities must be equal but got 2 and 1, respectively')
if layout in {torch.sparse_csr, torch.sparse_csc}:
yield ('indices and values mismatch of dimensionalities',
tensor([[0, 2, 4]]),
tensor([[0, 1, 0, 2]]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'values must have dimensionality > sum of batch and block dimensionalities \(=1 \+ 0\) but got 1')
else:
yield ('indices and values mismatch of dimensionalities',
tensor([[0, 2, 4]]),
tensor([[0, 1, 0, 2]]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'values must have dimensionality > sum of batch and block dimensionalities \(=1 \+ 2\) but got 3')
yield ('invalid size',
tensor([0, 2, 4]),
tensor([0, 1, 0, 2]),
values([1, 2, 3, 4]),
(2,),
r'tensor dimensionality must be sum of batch, base, and dense dimensionalities \(=0 \+ 2 \+ 0\) but got 1')
yield ('invalid batchsize',
tensor([[0, 2, 4]]),
tensor([[0, 1, 0, 2]]),
values([[1, 2, 3, 4]]),
shape((2, 2, 3), 1),
r'all batch dimensions of compressed_indices \(=\[1\]\), plain_indices \(=\[1\]\), '
r'and values \(=\[1\]\) must be equal to tensor batch dimensions \(=\[2\]\)')
if layout is torch.sparse_bsr:
yield ('invalid blocksize',
tensor([0, 2, 4]),
tensor([0, 1, 0, 2]),
tensor([[[1, 11]], [[2, 22]], [[3, 33]], [[4, 33]]]),
shape((2, 3)),
r'tensor shape\[1\] \(=3\) must be divisible with blocksize\[1\] \(=2\) as defined by values shape')
if layout is torch.sparse_bsc:
yield ('invalid blocksize',
tensor([0, 2, 4]),
tensor([0, 1, 0, 2]),
tensor([[[1, 11]], [[2, 22]], [[3, 33]], [[4, 33]]]),
shape((3, 2)),
r'tensor shape\[1\] \(=3\) must be divisible with blocksize\[1\] \(=2\) as defined by values shape')
yield ('invalid compressed_indices shape',
tensor([0, 2, 3, 4]),
tensor([0, 1, 0, 2]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'compressed_indices.shape\[-1\] must be equal to the number of compressed_indices_names \+ 1 \(=3\), but got 4')
yield ('invalid compressed_indices shape',
tensor([0, 2, 4]),
tensor([0, 1, 0, 1, 2]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'plain_indices.shape\[-1\] must be equal to nnz \(=4\) as defined by values.shape\[0\], but got 5')
yield ('compressed/plain_indices mismatch of dtype',
tensor([0, 2, 4], dtype=torch.int32),
tensor([0, 1, 0, 2], dtype=torch.int64),
values([1, 2, 3, 4]),
shape((2, 3)),
r'compressed_indices and plain_indices must have the same dtype, bot got Int and Long, respectively')
yield ('invalid compressed/plain_indices dtype',
tensor([0, 2, 4], dtype=torch.int16),
tensor([0, 1, 0, 2], dtype=torch.int16),
values([1, 2, 3, 4]),
shape((2, 3)),
r'compressed_indices and plain_indices dtype must be Int or Long, but got Short')
# CUDA kernel asserts are not recoverable, so we skip these for now
if torch.device(device).type == 'cpu':
yield ('invalid compressed_indices[0]',
tensor([1, 2, 4]),
tensor([0, 1, 0, 2]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'`compressed_indices\[..., 0\] == 0` is not satisfied.')
yield ('invalid compressed_indices[-1]',
tensor([0, 2, 5]),
tensor([0, 1, 0, 2]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'`compressed_indices\[..., -1\] == nnz` is not satisfied.')
yield ('invalid compressed_indices.diff(dim=-1)',
tensor([0, 0, 4]),
tensor([0, 1, 0, 2]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'0 <= compressed_indices\[..., 1:\] - compressed_indices\[..., :\-1\] <= plain_dim` is not satisfied.')
yield ('invalid compressed_indices.diff(dim=-1)',
tensor([0, 5, 4]),
tensor([0, 1, 0, 2]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'0 <= compressed_indices\[..., 1:\] - compressed_indices\[..., :\-1\] <= plain_dim` is not satisfied.')
yield ('invalid min(plain_indices)',
tensor([0, 2, 4]),
tensor([0, -1, 0, 3]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'`0 <= plain_indices < plain_dim` is not satisfied.')
yield ('invalid max(plain_indices)',
tensor([0, 2, 4]),
tensor([0, 1, 0, 3]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'`0 <= plain_indices < plain_dim` is not satisfied.')
yield ('non-coalesced',
tensor([0, 2, 4]),
tensor([1, 0, 0, 2]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'`plain_indices\[..., compressed_indices\[..., i - 1\]:compressed_indices\[..., i\]\] '
'for all i = 1, ..., compressed_dim '
'are sorted and distinct along the last dimension values` is not satisfied.')
if TEST_CUDA and torch.device(device).type == 'cpu':
yield ('indices and values mismatch of device',
torch.tensor([0, 2, 4]),
torch.tensor([0, 1, 0, 1]),
values([1, 2, 3, 4], device='cuda'),
shape((2, 3)),
r'device of compressed_indices \(=cpu\) must match device of values \(=cuda:0\)')
yield ('compressed_indices and values mismatch of device',
torch.tensor([0, 2, 4], device='cuda'),
torch.tensor([0, 1, 0, 1]),
values([1, 2, 3, 4]),
shape((2, 3)),
r'Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!')
yield ('compressed/plain_indices mismatch of device',
torch.tensor([0, 2, 4], device='cuda'),
torch.tensor([0, 1, 0, 1]),
values([1, 2, 3, 4], device='cuda'),
shape((2, 3)),
r'Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!')
if TEST_CUDA and torch.device(device).type == 'cuda' and torch.cuda.device_count() >= 2:
yield ('indices and values mismatch of device index',
torch.tensor([0, 2, 4], device='cuda:0'),
torch.tensor([0, 1, 0, 1], device='cuda:0'),
values([1, 2, 3, 4], device='cuda:1'),
shape((2, 3)),
r'device of compressed_indices \(=cuda:0\) must match device of values \(=cuda:1\)')
yield ('compressed_indices and values mismatch of device index',
torch.tensor([0, 2, 4], device='cuda:0'),
torch.tensor([0, 1, 0, 1], device='cuda:1'),
values([1, 2, 3, 4], device='cuda:0'),
shape((2, 3)),
r'Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cuda:1!')
@skipMeta
@all_sparse_compressed_layouts()
@parametrize('target', [subtest('validate_sparse_compressed_tensor_args'),
subtest('sparse_compressed_tensor'),
subtest('sparse_compressed_tensor_no_size')])
def test_invalid_input(self, layout, device, target):
for label, compressed_indices, plain_indices, values, size, errmsg in self._generate_invalid_input(layout, device):
if layout is torch.sparse_bsr:
errmsg = errmsg.replace('compressed_indices_name', 'row block').replace('plain_indices_name', 'column block')
elif layout is torch.sparse_bsc:
errmsg = errmsg.replace('compressed_indices_name', 'column block').replace('plain_indices_name', 'row block')
elif layout is torch.sparse_csr:
errmsg = errmsg.replace('compressed_indices_name', 'row').replace('plain_indices_name', 'column')
elif layout is torch.sparse_csc:
errmsg = errmsg.replace('compressed_indices_name', 'column').replace('plain_indices_name', 'row')
if layout in {torch.sparse_csr, torch.sparse_bsr}:
errmsg = errmsg.replace('compressed_indices', 'crow_indices') \
.replace('plain_indices', 'col_indices') \
.replace('plain_dim', 'ncols') \
.replace('compressed_dim', 'nrows')
else:
errmsg = errmsg.replace('compressed_indices', 'ccol_indices') \
.replace('plain_indices', 'row_indices') \
.replace('plain_dim', 'nrows') \
.replace('compressed_dim', 'ncols')
if target == 'sparse_compressed_tensor_no_size' and label in {
'invalid size', 'invalid batchsize', 'invalid compressed_indices shape', 'invalid max(plain_indices)',
'invalid blocksize'}:
# Skip invalid size input as a valid size is estimated for other inputs
continue
with self.assertRaisesRegex(RuntimeError, errmsg):
if target == 'validate_sparse_compressed_tensor_args':
torch._validate_sparse_compressed_tensor_args(compressed_indices, plain_indices, values, size, layout)
elif target == 'sparse_compressed_tensor':
torch.sparse_compressed_tensor(compressed_indices, plain_indices, values, size, layout=layout)
elif target == 'sparse_compressed_tensor_no_size':
torch.sparse_compressed_tensor(compressed_indices, plain_indices, values, layout=layout)
else:
raise NotImplementedError(target)
@skipMeta
@onlyCPU
@all_sparse_compressed_layouts()
def test_dim(self, layout):
for (compressed_indices, plain_indices, values), kwargs in self.generate_simple_inputs(layout, output_tensor=False):
size = kwargs['size']
batch_dim = compressed_indices.dim() - 1
sparse_dim = 2
block_dim = 2 if layout in {torch.sparse_bsr, torch.sparse_bsc} else 0
dense_dim = values.dim() - batch_dim - block_dim - 1
sparse = torch.sparse_compressed_tensor(compressed_indices, plain_indices, values, size, layout=layout)
self.assertEqual(sparse.sparse_dim(), sparse_dim)
self.assertEqual(sparse.dense_dim(), dense_dim)
@skipMeta
@all_sparse_compressed_layouts()
@dtypes(*all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16))
def test_to_dtype(self, layout, device, dtype):
# to_dense does not support hybrid inputs
for sparse in self.generate_simple_inputs(layout, dtype=dtype, device=device, enable_hybrid=False):
for to_dtype in all_types_and_complex_and(torch.bool, torch.half, torch.bfloat16):
sparse_to_dtype = sparse.to(to_dtype)
dense_to_dtype = sparse.to_dense().to(to_dtype)
self.assertEqual(sparse_to_dtype.to_dense(), dense_to_dtype)
@skipMeta
@all_sparse_compressed_layouts()
@dtypes(torch.double)
def test_pickle(self, layout, dtype, device):
import pickle
for sparse in self.generate_simple_inputs(layout, device=device, dtype=dtype):
serialized = pickle.dumps(sparse)
sparse_loaded = pickle.loads(serialized)
self.assertEqual(sparse, sparse_loaded)
@all_sparse_compressed_layouts()
@parametrize("index_dtype", [torch.int32, torch.int64])
@dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16, torch.bool))
def test_select_copy(self, device, dtype, index_dtype, layout):
def is_view_of(base, other):
# a shameless copy of TestViewOps.is_view_of
if ((not other._is_view() or
other is base or
other._base is not base or
base.device != other.device)):
return False
if base.device.type == 'cpu' or base.device.type == 'cuda':
if base._storage().data_ptr() != other._storage().data_ptr():
return False
return True
kwargs = dict(device=device, dtype=dtype, index_dtype=index_dtype)
for sparse, dense in zip(self.generate_simple_inputs(layout, **kwargs),
self.generate_simple_inputs(torch.strided, **kwargs)):
if layout in {torch.sparse_csr, torch.sparse_bsr}:
n_batchdim = sparse.crow_indices().ndim - 1
elif layout in {torch.sparse_csc, torch.sparse_bsc}:
n_batchdim = sparse.ccol_indices().ndim - 1
else:
assert 0 # unreachable
self.assertEqual(sparse, dense)
for dim in range(sparse.ndim):
if sparse.shape[dim] == 0:
with self.assertRaisesRegex(IndexError, "index 0 out of range for tensor of size"):
torch.select_copy(sparse, dim, 0)
with self.assertRaisesRegex(IndexError, "index 0 out of range for tensor of size"):
torch.select_copy(dense, dim, 0)
elif n_batchdim and dim >= n_batchdim and dim < n_batchdim + 2:
with self.assertRaisesRegex(
RuntimeError,
"selecting sparse dimensions is not implemented for batched sparse compressed tensors"):
torch.select_copy(sparse, dim, 0)
else:
for index in {0, sparse.shape[dim] // 2, sparse.shape[dim] - 1}:
dense_select = torch.select_copy(dense, dim, index)
sparse_select = torch.select_copy(sparse, dim, index)
self.assertEqual(sparse_select, dense_select)
self.assertFalse(is_view_of(sparse_select.values(), sparse.values()))
def _npref_block_addmm_addmv(c, a, b, alpha, beta):
return alpha * (a @ b) + beta * c
class TestSparseCSR(TestCase):
def test_csr_stride(self):
a = self.genSparseCSRTensor((3, 3), 3, dtype=torch.float, device=self.device_type, index_dtype=torch.int64)
with self.assertRaisesRegex(RuntimeError, "Sparse CSR tensors do not have strides"):
a.stride()
with self.assertRaisesRegex(RuntimeError, "Sparse CSR tensors do not have strides"):
a.stride(-1)
def test_csr_storage(self):
a = self.genSparseCSRTensor((3, 3), 3, dtype=torch.float, device=self.device_type, index_dtype=torch.int64)
with self.assertRaisesRegex(RuntimeError, "Cannot access storage of SparseCsrTensorImpl"):
a.storage()
def test_csr_is_contiguous(self):
a = self.genSparseCSRTensor((3, 3), 3, dtype=torch.float, device=self.device_type, index_dtype=torch.int64)
with self.assertRaisesRegex(RuntimeError, "Sparse CSR tensors do not have is_contiguous"):
a.is_contiguous()
def test_csr_double_to_sparse_csr(self):
a = self.genSparseCSRTensor((3, 3), 3, dtype=torch.float, device=self.device_type, index_dtype=torch.int64)
a.to_sparse_csr().to_sparse_csr()
@all_sparse_compressed_layouts()
@parametrize("index_dtype", [torch.int32, torch.int64])
@dtypes(*all_types_and_complex_and(torch.half, torch.bfloat16, torch.bool))
def test_select(self, device, dtype, index_dtype, layout):
compressed_indices_mth = {
torch.sparse_csr: torch.Tensor.crow_indices,
torch.sparse_bsr: torch.Tensor.crow_indices,
torch.sparse_csc: torch.Tensor.ccol_indices,
torch.sparse_bsc: torch.Tensor.ccol_indices,
}[layout]
plain_indices_mth = {
torch.sparse_csr: torch.Tensor.col_indices,
torch.sparse_bsr: torch.Tensor.col_indices,
torch.sparse_csc: torch.Tensor.row_indices,
torch.sparse_bsc: torch.Tensor.row_indices,
}[layout]
create_tensor_mth = {
torch.sparse_csr: torch.sparse_csr_tensor,
torch.sparse_bsr: torch.sparse_bsr_tensor,
torch.sparse_csc: torch.sparse_csc_tensor,
torch.sparse_bsc: torch.sparse_bsc_tensor,
}[layout]
shape = (2, 3, 6, 10)
nnz = 6
blocksize = (2, 2) if layout in {torch.sparse_bsr, torch.sparse_bsc} else ()
sparse = self.genSparseCompressedTensor(
shape, nnz, device=device, layout=layout, dtype=dtype, index_dtype=index_dtype, blocksize=blocksize)
comp_indices = compressed_indices_mth(sparse)
plain_indices = plain_indices_mth(sparse)
values = sparse.values()
# select from batch dimensions
sparse_selected12 = sparse.select(1, 2)
expected_sparse_selected12 = create_tensor_mth(comp_indices.select(1, 2).contiguous(),
plain_indices.select(1, 2).contiguous(),
values.select(1, 2).contiguous(),
size=(2, 6, 10),
dtype=dtype,
device=device)
self.assertEqual(expected_sparse_selected12, sparse_selected12)
# selecting rows/col with batch dims not allowed
sparse_non_batched = sparse[0, 0]
# select from sparse dimensions
for select_args in [(0, 0), (1, 1)]:
sparse_selected = sparse_non_batched.select(*select_args)
dense_selected = sparse_non_batched.to_dense().select(*select_args)
self.assertEqual(dense_selected, sparse_selected)
self.assertEqual(sparse[0, 0, 0, 0], sparse.to_dense()[0, 0, 0, 0])
# assigning to sparse through indexing is disabled
with self.assertRaisesRegex(TypeError, "Cannot assign to a sparse tensor"):
sparse[0, 0, 0, 0] = 99.0
# select from sparse dimensions without removing batch dims
msg = "selecting sparse dimensions is not implemented for batched sparse compressed tensors."
with self.assertRaisesRegex(RuntimeError, msg):