-
-
Notifications
You must be signed in to change notification settings - Fork 865
/
cusparse.py
2092 lines (1734 loc) · 69.3 KB
/
cusparse.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
863
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
import functools as _functools
import numpy as _numpy
import platform as _platform
import cupy as _cupy
from cupy_backends.cuda.api import driver as _driver
from cupy_backends.cuda.api import runtime as _runtime
from cupy_backends.cuda.libs import cusparse as _cusparse
from cupy._core import _dtype
from cupy.cuda import device as _device
from cupy.cuda import stream as _stream
from cupy import _util
import cupyx.scipy.sparse
class MatDescriptor(object):
def __init__(self, descriptor):
self.descriptor = descriptor
@classmethod
def create(cls):
descr = _cusparse.createMatDescr()
return MatDescriptor(descr)
def __reduce__(self):
return self.create, ()
def __del__(self, is_shutting_down=_util.is_shutting_down):
if is_shutting_down():
return
if self.descriptor:
_cusparse.destroyMatDescr(self.descriptor)
self.descriptor = None
def set_mat_type(self, typ):
_cusparse.setMatType(self.descriptor, typ)
def set_mat_index_base(self, base):
_cusparse.setMatIndexBase(self.descriptor, base)
def set_mat_fill_mode(self, fill_mode):
_cusparse.setMatFillMode(self.descriptor, fill_mode)
def set_mat_diag_type(self, diag_type):
_cusparse.setMatDiagType(self.descriptor, diag_type)
def _cast_common_type(*xs):
dtypes = [x.dtype for x in xs if x is not None]
dtype = _functools.reduce(_numpy.promote_types, dtypes)
return [x.astype(dtype) if x is not None and x.dtype != dtype else x
for x in xs]
def _transpose_flag(trans):
if trans:
return _cusparse.CUSPARSE_OPERATION_TRANSPOSE
else:
return _cusparse.CUSPARSE_OPERATION_NON_TRANSPOSE
def _call_cusparse(name, dtype, *args):
if dtype == 'f':
prefix = 's'
elif dtype == 'd':
prefix = 'd'
elif dtype == 'F':
prefix = 'c'
elif dtype == 'D':
prefix = 'z'
else:
raise TypeError
f = getattr(_cusparse, prefix name)
return f(*args)
_available_cusparse_version = {
'csrmv': (8000, 11000),
'csrmvEx': (8000, 11000), # TODO(anaruse): failure in cuSparse 11.0
'csrmm': (8000, 11000),
'csrmm2': (8000, 11000),
'csrgeam': (8000, 11000),
'csrgeam2': (9020, None),
'csrgemm': (8000, 11000),
'csrgemm2': (8000, 12000),
'gthr': (8000, 12000),
# Generic APIs are not available on CUDA 10.2 on Windows.
'spmv': ({'Linux': 10200, 'Windows': 11000}, None),
# accuracy bugs in cuSparse 10.3.0
'spmm': ({'Linux': 10301, 'Windows': 11000}, None),
'csr2dense': (8000, 12000),
'csc2dense': (8000, 12000),
'csrsort': (8000, None),
'cscsort': (8000, None),
'coosort': (8000, None),
'coo2csr': (8000, None),
'csr2coo': (8000, None),
'csr2csc': (8000, 11000),
'csc2csr': (8000, 11000), # the entity is csr2csc
'csr2cscEx2': (10200, None),
'csc2csrEx2': (10200, None), # the entity is csr2cscEx2
'dense2csc': (8000, None),
'dense2csr': (8000, None),
'csr2csr_compress': (8000, None),
'csrsm2': (9020, 12000),
'csrilu02': (8000, None),
'denseToSparse': (11300, None),
'sparseToDense': (11300, None),
'spgemm': (11100, None),
'spsm': (11600, None), # CUDA 11.3.1
}
_available_hipsparse_version = {
# For APIs supported by CUDA but not yet by HIP, we still need them here
# so that our test suite can cover both platforms.
'csrmv': (305, None),
'csrmvEx': (_numpy.inf, None),
'csrmm': (305, None),
'csrmm2': (305, None),
'csrgeam': (305, None),
'csrgeam2': (305, None),
'csrgemm': (305, None),
'csrgemm2': (305, None),
'gthr': (305, None),
'spmv': (402, None),
'spmm': (402, None),
'csr2dense': (305, None),
'csc2dense': (305, None),
'csrsort': (305, None),
'cscsort': (305, None),
'coosort': (305, None),
'coo2csr': (305, None),
'csr2coo': (305, None),
'csr2csc': (305, None),
'csc2csr': (305, None), # the entity is csr2csc
'csr2cscEx2': (_numpy.inf, None),
'csc2csrEx2': (_numpy.inf, None), # the entity is csr2cscEx2
'dense2csc': (305, None),
'dense2csr': (305, None),
'csr2csr_compress': (305, None),
'csrsm2': (305, None), # avaiable since 305 but seems buggy
'csrilu02': (305, None),
'denseToSparse': (402, None),
'sparseToDense': (402, None),
'spgemm': (_numpy.inf, None),
'spsm': (50000000, None),
}
def _get_avail_version_from_spec(x):
if isinstance(x, dict):
os_name = _platform.system()
if os_name not in x:
msg = 'No version information specified for the OS: {}'.format(
os_name)
raise ValueError(msg)
return x[os_name]
return x
@_util.memoize()
def check_availability(name):
if not _runtime.is_hip:
available_version = _available_cusparse_version
version = _cusparse.get_build_version()
else:
available_version = _available_hipsparse_version
version = _driver.get_build_version() # = HIP_VERSION
if name not in available_version:
msg = 'No available version information specified for {}'.format(name)
raise ValueError(msg)
version_added, version_removed = available_version[name]
version_added = _get_avail_version_from_spec(version_added)
version_removed = _get_avail_version_from_spec(version_removed)
if version_added is not None and version < version_added:
return False
if version_removed is not None and version >= version_removed:
return False
return True
def getVersion() -> int:
return _cusparse.getVersion(_device.get_cusparse_handle())
def csrmv(a, x, y=None, alpha=1, beta=0, transa=False):
"""Matrix-vector product for a CSR-matrix and a dense vector.
.. math::
y = \\alpha * o_a(A) x \\beta y,
where :math:`o_a` is a transpose function when ``transa`` is ``True`` and
is an identity function otherwise.
Args:
a (cupyx.cusparse.csr_matrix): Matrix A.
x (cupy.ndarray): Vector x.
y (cupy.ndarray or None): Vector y. It must be F-contiguous.
alpha (float): Coefficient for x.
beta (float): Coefficient for y.
transa (bool): If ``True``, transpose of ``A`` is used.
Returns:
cupy.ndarray: Calculated ``y``.
"""
if not check_availability('csrmv'):
raise RuntimeError('csrmv is not available.')
assert y is None or y.flags.f_contiguous
a_shape = a.shape if not transa else a.shape[::-1]
if a_shape[1] != len(x):
raise ValueError('dimension mismatch')
handle = _device.get_cusparse_handle()
m, n = a_shape
a, x, y = _cast_common_type(a, x, y)
dtype = a.dtype
if y is None:
y = _cupy.zeros(m, dtype)
alpha = _numpy.array(alpha, dtype).ctypes
beta = _numpy.array(beta, dtype).ctypes
_call_cusparse(
'csrmv', dtype,
handle, _transpose_flag(transa),
a.shape[0], a.shape[1], a.nnz, alpha.data, a._descr.descriptor,
a.data.data.ptr, a.indptr.data.ptr, a.indices.data.ptr,
x.data.ptr, beta.data, y.data.ptr)
return y
def csrmvExIsAligned(a, x, y=None):
"""Check if the pointers of arguments for csrmvEx are aligned or not
Args:
a (cupyx.cusparse.csr_matrix): Matrix A.
x (cupy.ndarray): Vector x.
y (cupy.ndarray or None): Vector y.
Check if a, x, y pointers are aligned by 128 bytes as
required by csrmvEx.
Returns:
bool:
``True`` if all pointers are aligned.
``False`` if otherwise.
"""
if a.data.data.ptr % 128 != 0:
return False
if a.indptr.data.ptr % 128 != 0:
return False
if a.indices.data.ptr % 128 != 0:
return False
if x.data.ptr % 128 != 0:
return False
if y is not None and y.data.ptr % 128 != 0:
return False
return True
def csrmvEx(a, x, y=None, alpha=1, beta=0, merge_path=True):
"""Matrix-vector product for a CSR-matrix and a dense vector.
.. math::
y = \\alpha * A x \\beta y,
Args:
a (cupyx.cusparse.csr_matrix): Matrix A.
x (cupy.ndarray): Vector x.
y (cupy.ndarray or None): Vector y. It must be F-contiguous.
alpha (float): Coefficient for x.
beta (float): Coefficient for y.
merge_path (bool): If ``True``, merge path algorithm is used.
All pointers must be aligned with 128 bytes.
Returns:
cupy.ndarray: Calculated ``y``.
"""
if not check_availability('csrmvEx'):
raise RuntimeError('csrmvEx is not available.')
assert y is None or y.flags.f_contiguous
if a.shape[1] != len(x):
raise ValueError('dimension mismatch')
handle = _device.get_cusparse_handle()
m, n = a.shape
a, x, y = _cast_common_type(a, x, y)
dtype = a.dtype
if y is None:
y = _cupy.zeros(m, dtype)
datatype = _dtype.to_cuda_dtype(dtype)
algmode = _cusparse.CUSPARSE_ALG_MERGE_PATH if \
merge_path else _cusparse.CUSPARSE_ALG_NAIVE
transa_flag = _cusparse.CUSPARSE_OPERATION_NON_TRANSPOSE
alpha = _numpy.array(alpha, dtype).ctypes
beta = _numpy.array(beta, dtype).ctypes
assert csrmvExIsAligned(a, x, y)
bufferSize = _cusparse.csrmvEx_bufferSize(
handle, algmode, transa_flag,
a.shape[0], a.shape[1], a.nnz, alpha.data, datatype,
a._descr.descriptor, a.data.data.ptr, datatype,
a.indptr.data.ptr, a.indices.data.ptr,
x.data.ptr, datatype, beta.data, datatype,
y.data.ptr, datatype, datatype)
buf = _cupy.empty(bufferSize, 'b')
assert buf.data.ptr % 128 == 0
_cusparse.csrmvEx(
handle, algmode, transa_flag,
a.shape[0], a.shape[1], a.nnz, alpha.data, datatype,
a._descr.descriptor, a.data.data.ptr, datatype,
a.indptr.data.ptr, a.indices.data.ptr,
x.data.ptr, datatype, beta.data, datatype,
y.data.ptr, datatype, datatype, buf.data.ptr)
return y
def csrmm(a, b, c=None, alpha=1, beta=0, transa=False):
"""Matrix-matrix product for a CSR-matrix and a dense matrix.
.. math::
C = \\alpha o_a(A) B \\beta C,
where :math:`o_a` is a transpose function when ``transa`` is ``True`` and
is an identity function otherwise.
Args:
a (cupyx.scipy.sparse.csr): Sparse matrix A.
b (cupy.ndarray): Dense matrix B. It must be F-contiguous.
c (cupy.ndarray or None): Dense matrix C. It must be F-contiguous.
alpha (float): Coefficient for AB.
beta (float): Coefficient for C.
transa (bool): If ``True``, transpose of A is used.
Returns:
cupy.ndarray: Calculated C.
"""
if not check_availability('csrmm'):
raise RuntimeError('csrmm is not available.')
assert a.ndim == b.ndim == 2
assert b.flags.f_contiguous
assert c is None or c.flags.f_contiguous
a_shape = a.shape if not transa else a.shape[::-1]
if a_shape[1] != b.shape[0]:
raise ValueError('dimension mismatch')
handle = _device.get_cusparse_handle()
m, k = a_shape
n = b.shape[1]
a, b, c = _cast_common_type(a, b, c)
if c is None:
c = _cupy.zeros((m, n), a.dtype, 'F')
ldb = k
ldc = m
alpha = _numpy.array(alpha, a.dtype).ctypes
beta = _numpy.array(beta, a.dtype).ctypes
_call_cusparse(
'csrmm', a.dtype,
handle, _transpose_flag(transa),
a.shape[0], n, a.shape[1], a.nnz,
alpha.data, a._descr.descriptor, a.data.data.ptr,
a.indptr.data.ptr, a.indices.data.ptr,
b.data.ptr, ldb, beta.data, c.data.ptr, ldc)
return c
def csrmm2(a, b, c=None, alpha=1.0, beta=0.0, transa=False, transb=False):
"""Matrix-matrix product for a CSR-matrix and a dense matrix.
.. math::
C = \\alpha o_a(A) o_b(B) \\beta C,
where :math:`o_a` and :math:`o_b` are transpose functions when ``transa``
and ``tranb`` are ``True`` respectively. And they are identity functions
otherwise.
It is forbidden that both ``transa`` and ``transb`` are ``True`` in
cuSPARSE specification.
Args:
a (cupyx.scipy.sparse.csr): Sparse matrix A.
b (cupy.ndarray): Dense matrix B. It must be F-contiguous.
c (cupy.ndarray or None): Dense matrix C. It must be F-contiguous.
alpha (float): Coefficient for AB.
beta (float): Coefficient for C.
transa (bool): If ``True``, transpose of A is used.
transb (bool): If ``True``, transpose of B is used.
Returns:
cupy.ndarray: Calculated C.
"""
if not check_availability('csrmm2'):
raise RuntimeError('csrmm2 is not available.')
assert a.ndim == b.ndim == 2
assert a.has_canonical_format
assert b.flags.f_contiguous
assert c is None or c.flags.f_contiguous
assert not (transa and transb)
a_shape = a.shape if not transa else a.shape[::-1]
b_shape = b.shape if not transb else b.shape[::-1]
if a_shape[1] != b_shape[0]:
raise ValueError('dimension mismatch')
handle = _device.get_cusparse_handle()
m, k = a_shape
n = b_shape[1]
a, b, c = _cast_common_type(a, b, c)
if c is None:
c = _cupy.zeros((m, n), a.dtype, 'F')
ldb = b.shape[0]
ldc = c.shape[0]
op_a = _transpose_flag(transa)
op_b = _transpose_flag(transb)
alpha = _numpy.array(alpha, a.dtype).ctypes
beta = _numpy.array(beta, a.dtype).ctypes
_call_cusparse(
'csrmm2', a.dtype,
handle, op_a, op_b, a.shape[0], n, a.shape[1], a.nnz,
alpha.data, a._descr.descriptor, a.data.data.ptr,
a.indptr.data.ptr, a.indices.data.ptr,
b.data.ptr, ldb, beta.data, c.data.ptr, ldc)
return c
def csrgeam(a, b, alpha=1, beta=1):
"""Matrix-matrix addition.
.. math::
C = \\alpha A \\beta B
Args:
a (cupyx.scipy.sparse.csr_matrix): Sparse matrix A.
b (cupyx.scipy.sparse.csr_matrix): Sparse matrix B.
alpha (float): Coefficient for A.
beta (float): Coefficient for B.
Returns:
cupyx.scipy.sparse.csr_matrix: Result matrix.
"""
if not check_availability('csrgeam'):
raise RuntimeError('csrgeam is not available.')
if not isinstance(a, cupyx.scipy.sparse.csr_matrix):
raise TypeError('unsupported type (actual: {})'.format(type(a)))
if not isinstance(b, cupyx.scipy.sparse.csr_matrix):
raise TypeError('unsupported type (actual: {})'.format(type(b)))
assert a.has_canonical_format
assert b.has_canonical_format
if a.shape != b.shape:
raise ValueError('inconsistent shapes')
handle = _device.get_cusparse_handle()
m, n = a.shape
a, b = _cast_common_type(a, b)
nnz = _numpy.empty((), 'i')
_cusparse.setPointerMode(
handle, _cusparse.CUSPARSE_POINTER_MODE_HOST)
c_descr = MatDescriptor.create()
c_indptr = _cupy.empty(m 1, 'i')
_cusparse.xcsrgeamNnz(
handle, m, n,
a._descr.descriptor, a.nnz, a.indptr.data.ptr, a.indices.data.ptr,
b._descr.descriptor, b.nnz, b.indptr.data.ptr, b.indices.data.ptr,
c_descr.descriptor, c_indptr.data.ptr, nnz.ctypes.data)
c_indices = _cupy.empty(int(nnz), 'i')
c_data = _cupy.empty(int(nnz), a.dtype)
alpha = _numpy.array(alpha, a.dtype).ctypes
beta = _numpy.array(beta, a.dtype).ctypes
_call_cusparse(
'csrgeam', a.dtype,
handle, m, n, alpha.data,
a._descr.descriptor, a.nnz, a.data.data.ptr,
a.indptr.data.ptr, a.indices.data.ptr, beta.data,
b._descr.descriptor, b.nnz, b.data.data.ptr,
b.indptr.data.ptr, b.indices.data.ptr,
c_descr.descriptor, c_data.data.ptr, c_indptr.data.ptr,
c_indices.data.ptr)
c = cupyx.scipy.sparse.csr_matrix(
(c_data, c_indices, c_indptr), shape=a.shape)
c._has_canonical_format = True
return c
def csrgeam2(a, b, alpha=1, beta=1):
"""Matrix-matrix addition.
.. math::
C = \\alpha A \\beta B
Args:
a (cupyx.scipy.sparse.csr_matrix): Sparse matrix A.
b (cupyx.scipy.sparse.csr_matrix): Sparse matrix B.
alpha (float): Coefficient for A.
beta (float): Coefficient for B.
Returns:
cupyx.scipy.sparse.csr_matrix: Result matrix.
"""
if not check_availability('csrgeam2'):
raise RuntimeError('csrgeam2 is not available.')
if not isinstance(a, cupyx.scipy.sparse.csr_matrix):
raise TypeError('unsupported type (actual: {})'.format(type(a)))
if not isinstance(b, cupyx.scipy.sparse.csr_matrix):
raise TypeError('unsupported type (actual: {})'.format(type(b)))
assert a.has_canonical_format
assert b.has_canonical_format
if a.shape != b.shape:
raise ValueError('inconsistent shapes')
handle = _device.get_cusparse_handle()
m, n = a.shape
a, b = _cast_common_type(a, b)
nnz = _numpy.empty((), 'i')
_cusparse.setPointerMode(
handle, _cusparse.CUSPARSE_POINTER_MODE_HOST)
alpha = _numpy.array(alpha, a.dtype).ctypes
beta = _numpy.array(beta, a.dtype).ctypes
c_descr = MatDescriptor.create()
c_indptr = _cupy.empty(m 1, 'i')
null_ptr = 0
buff_size = _call_cusparse(
'csrgeam2_bufferSizeExt', a.dtype,
handle, m, n, alpha.data, a._descr.descriptor, a.nnz, a.data.data.ptr,
a.indptr.data.ptr, a.indices.data.ptr, beta.data, b._descr.descriptor,
b.nnz, b.data.data.ptr, b.indptr.data.ptr, b.indices.data.ptr,
c_descr.descriptor, null_ptr, c_indptr.data.ptr, null_ptr)
buff = _cupy.empty(buff_size, _numpy.int8)
_cusparse.xcsrgeam2Nnz(
handle, m, n, a._descr.descriptor, a.nnz, a.indptr.data.ptr,
a.indices.data.ptr, b._descr.descriptor, b.nnz, b.indptr.data.ptr,
b.indices.data.ptr, c_descr.descriptor, c_indptr.data.ptr,
nnz.ctypes.data, buff.data.ptr)
c_indices = _cupy.empty(int(nnz), 'i')
c_data = _cupy.empty(int(nnz), a.dtype)
_call_cusparse(
'csrgeam2', a.dtype,
handle, m, n, alpha.data, a._descr.descriptor, a.nnz, a.data.data.ptr,
a.indptr.data.ptr, a.indices.data.ptr, beta.data, b._descr.descriptor,
b.nnz, b.data.data.ptr, b.indptr.data.ptr, b.indices.data.ptr,
c_descr.descriptor, c_data.data.ptr, c_indptr.data.ptr,
c_indices.data.ptr, buff.data.ptr)
c = cupyx.scipy.sparse.csr_matrix(
(c_data, c_indices, c_indptr), shape=a.shape)
c._has_canonical_format = True
return c
def csrgemm(a, b, transa=False, transb=False):
"""Matrix-matrix product for CSR-matrix.
math::
C = op(A) op(B),
Args:
a (cupyx.scipy.sparse.csr_matrix): Sparse matrix A.
b (cupyx.scipy.sparse.csr_matrix): Sparse matrix B.
transa (bool): If ``True``, transpose of A is used.
transb (bool): If ``True``, transpose of B is used.
Returns:
cupyx.scipy.sparse.csr_matrix: Calculated C.
"""
if not check_availability('csrgemm'):
raise RuntimeError('csrgemm is not available.')
assert a.ndim == b.ndim == 2
assert a.has_canonical_format
assert b.has_canonical_format
a_shape = a.shape if not transa else a.shape[::-1]
b_shape = b.shape if not transb else b.shape[::-1]
if a_shape[1] != b_shape[0]:
raise ValueError('dimension mismatch')
handle = _device.get_cusparse_handle()
m, k = a_shape
n = b_shape[1]
a, b = _cast_common_type(a, b)
if a.nnz == 0 or b.nnz == 0:
return cupyx.scipy.sparse.csr_matrix((m, n), dtype=a.dtype)
op_a = _transpose_flag(transa)
op_b = _transpose_flag(transb)
nnz = _numpy.empty((), 'i')
_cusparse.setPointerMode(
handle, _cusparse.CUSPARSE_POINTER_MODE_HOST)
c_descr = MatDescriptor.create()
c_indptr = _cupy.empty(m 1, 'i')
_cusparse.xcsrgemmNnz(
handle, op_a, op_b, m, n, k, a._descr.descriptor, a.nnz,
a.indptr.data.ptr, a.indices.data.ptr, b._descr.descriptor, b.nnz,
b.indptr.data.ptr, b.indices.data.ptr, c_descr.descriptor,
c_indptr.data.ptr, nnz.ctypes.data)
c_indices = _cupy.empty(int(nnz), 'i')
c_data = _cupy.empty(int(nnz), a.dtype)
_call_cusparse(
'csrgemm', a.dtype,
handle, op_a, op_b, m, n, k, a._descr.descriptor, a.nnz,
a.data.data.ptr, a.indptr.data.ptr, a.indices.data.ptr,
b._descr.descriptor, b.nnz, b.data.data.ptr, b.indptr.data.ptr,
b.indices.data.ptr,
c_descr.descriptor, c_data.data.ptr, c_indptr.data.ptr,
c_indices.data.ptr)
c = cupyx.scipy.sparse.csr_matrix(
(c_data, c_indices, c_indptr), shape=(m, n))
c._has_canonical_format = True
return c
def csrgemm2(a, b, d=None, alpha=1, beta=1):
"""Matrix-matrix product for CSR-matrix.
math::
C = alpha * A * B beta * D
Args:
a (cupyx.scipy.sparse.csr_matrix): Sparse matrix A.
b (cupyx.scipy.sparse.csr_matrix): Sparse matrix B.
d (cupyx.scipy.sparse.csr_matrix or None): Sparse matrix D.
alpha (scalar): Coefficient
beta (scalar): Coefficient
Returns:
cupyx.scipy.sparse.csr_matrix
"""
if not check_availability('csrgemm2'):
raise RuntimeError('csrgemm2 is not available.')
assert a.ndim == b.ndim == 2
if not isinstance(a, cupyx.scipy.sparse.csr_matrix):
raise TypeError('unsupported type (actual: {})'.format(type(a)))
if not isinstance(b, cupyx.scipy.sparse.csr_matrix):
raise TypeError('unsupported type (actual: {})'.format(type(b)))
assert a.has_canonical_format
assert b.has_canonical_format
if a.shape[1] != b.shape[0]:
raise ValueError('mismatched shape')
if d is not None:
assert d.ndim == 2
if not isinstance(d, cupyx.scipy.sparse.csr_matrix):
raise TypeError('unsupported type (actual: {})'.format(type(d)))
assert d.has_canonical_format
if a.shape[0] != d.shape[0] or b.shape[1] != d.shape[1]:
raise ValueError('mismatched shape')
if _runtime.is_hip and _driver.get_build_version() < 402:
raise RuntimeError('d != None is supported since ROCm 4.2.0')
handle = _device.get_cusparse_handle()
m, k = a.shape
_, n = b.shape
if d is None:
a, b = _cast_common_type(a, b)
else:
a, b, d = _cast_common_type(a, b, d)
info = _cusparse.createCsrgemm2Info()
alpha = _numpy.array(alpha, a.dtype).ctypes
null_ptr = 0
if d is None:
beta_data = null_ptr
d_descr = MatDescriptor.create()
d_nnz = 0
d_data = null_ptr
d_indptr = null_ptr
d_indices = null_ptr
else:
beta = _numpy.array(beta, a.dtype).ctypes
beta_data = beta.data
d_descr = d._descr
d_nnz = d.nnz
d_data = d.data.data.ptr
d_indptr = d.indptr.data.ptr
d_indices = d.indices.data.ptr
buff_size = _call_cusparse(
'csrgemm2_bufferSizeExt', a.dtype,
handle, m, n, k, alpha.data, a._descr.descriptor, a.nnz,
a.indptr.data.ptr, a.indices.data.ptr, b._descr.descriptor, b.nnz,
b.indptr.data.ptr, b.indices.data.ptr, beta_data, d_descr.descriptor,
d_nnz, d_indptr, d_indices, info)
buff = _cupy.empty(buff_size, _numpy.int8)
c_nnz = _numpy.empty((), 'i')
_cusparse.setPointerMode(handle, _cusparse.CUSPARSE_POINTER_MODE_HOST)
c_descr = MatDescriptor.create()
c_indptr = _cupy.empty(m 1, 'i')
_cusparse.xcsrgemm2Nnz(
handle, m, n, k, a._descr.descriptor, a.nnz, a.indptr.data.ptr,
a.indices.data.ptr, b._descr.descriptor, b.nnz, b.indptr.data.ptr,
b.indices.data.ptr, d_descr.descriptor, d_nnz, d_indptr, d_indices,
c_descr.descriptor, c_indptr.data.ptr, c_nnz.ctypes.data, info,
buff.data.ptr)
c_indices = _cupy.empty(int(c_nnz), 'i')
c_data = _cupy.empty(int(c_nnz), a.dtype)
_call_cusparse(
'csrgemm2', a.dtype,
handle, m, n, k, alpha.data, a._descr.descriptor, a.nnz,
a.data.data.ptr, a.indptr.data.ptr, a.indices.data.ptr,
b._descr.descriptor, b.nnz, b.data.data.ptr, b.indptr.data.ptr,
b.indices.data.ptr, beta_data, d_descr.descriptor, d_nnz, d_data,
d_indptr, d_indices, c_descr.descriptor, c_data.data.ptr,
c_indptr.data.ptr, c_indices.data.ptr, info, buff.data.ptr)
c = cupyx.scipy.sparse.csr_matrix(
(c_data, c_indices, c_indptr), shape=(m, n))
c._has_canonical_format = True
_cusparse.destroyCsrgemm2Info(info)
return c
def csr2dense(x, out=None):
"""Converts CSR-matrix to a dense matrix.
Args:
x (cupyx.scipy.sparse.csr_matrix): A sparse matrix to convert.
out (cupy.ndarray or None): A dense metrix to store the result.
It must be F-contiguous.
Returns:
cupy.ndarray: Converted result.
"""
if not check_availability('csr2dense'):
raise RuntimeError('csr2dense is not available.')
dtype = x.dtype
assert dtype.char in 'fdFD'
if out is None:
out = _cupy.empty(x.shape, dtype=dtype, order='F')
else:
assert out.flags.f_contiguous
handle = _device.get_cusparse_handle()
_call_cusparse(
'csr2dense', x.dtype,
handle, x.shape[0], x.shape[1], x._descr.descriptor,
x.data.data.ptr, x.indptr.data.ptr, x.indices.data.ptr,
out.data.ptr, x.shape[0])
return out
def csc2dense(x, out=None):
"""Converts CSC-matrix to a dense matrix.
Args:
x (cupyx.scipy.sparse.csc_matrix): A sparse matrix to convert.
out (cupy.ndarray or None): A dense metrix to store the result.
It must be F-contiguous.
Returns:
cupy.ndarray: Converted result.
"""
if not check_availability('csc2dense'):
raise RuntimeError('csc2dense is not available.')
dtype = x.dtype
assert dtype.char in 'fdFD'
if out is None:
out = _cupy.empty(x.shape, dtype=dtype, order='F')
else:
assert out.flags.f_contiguous
handle = _device.get_cusparse_handle()
_call_cusparse(
'csc2dense', x.dtype,
handle, x.shape[0], x.shape[1], x._descr.descriptor,
x.data.data.ptr, x.indices.data.ptr, x.indptr.data.ptr,
out.data.ptr, x.shape[0])
return out
def csrsort(x):
"""Sorts indices of CSR-matrix in place.
Args:
x (cupyx.scipy.sparse.csr_matrix): A sparse matrix to sort.
"""
if not check_availability('csrsort'):
raise RuntimeError('csrsort is not available.')
nnz = x.nnz
if nnz == 0:
return
handle = _device.get_cusparse_handle()
m, n = x.shape
buffer_size = _cusparse.xcsrsort_bufferSizeExt(
handle, m, n, nnz, x.indptr.data.ptr,
x.indices.data.ptr)
buf = _cupy.empty(buffer_size, 'b')
P = _cupy.empty(nnz, 'i')
data_orig = x.data.copy()
_cusparse.createIdentityPermutation(handle, nnz, P.data.ptr)
_cusparse.xcsrsort(
handle, m, n, nnz, x._descr.descriptor, x.indptr.data.ptr,
x.indices.data.ptr, P.data.ptr, buf.data.ptr)
if check_availability('gthr'):
_call_cusparse(
'gthr', x.dtype,
handle, nnz, data_orig.data.ptr, x.data.data.ptr,
P.data.ptr, _cusparse.CUSPARSE_INDEX_BASE_ZERO)
else:
desc_x = SpVecDescriptor.create(P, x.data)
desc_y = DnVecDescriptor.create(data_orig)
_cusparse.gather(handle, desc_y.desc, desc_x.desc)
def cscsort(x):
"""Sorts indices of CSC-matrix in place.
Args:
x (cupyx.scipy.sparse.csc_matrix): A sparse matrix to sort.
"""
if not check_availability('cscsort'):
raise RuntimeError('cscsort is not available.')
nnz = x.nnz
if nnz == 0:
return
handle = _device.get_cusparse_handle()
m, n = x.shape
buffer_size = _cusparse.xcscsort_bufferSizeExt(
handle, m, n, nnz, x.indptr.data.ptr,
x.indices.data.ptr)
buf = _cupy.empty(buffer_size, 'b')
P = _cupy.empty(nnz, 'i')
data_orig = x.data.copy()
_cusparse.createIdentityPermutation(handle, nnz, P.data.ptr)
_cusparse.xcscsort(
handle, m, n, nnz, x._descr.descriptor, x.indptr.data.ptr,
x.indices.data.ptr, P.data.ptr, buf.data.ptr)
if check_availability('gthr'):
_call_cusparse(
'gthr', x.dtype,
handle, nnz, data_orig.data.ptr, x.data.data.ptr,
P.data.ptr, _cusparse.CUSPARSE_INDEX_BASE_ZERO)
else:
desc_x = SpVecDescriptor.create(P, x.data)
desc_y = DnVecDescriptor.create(data_orig)
_cusparse.gather(handle, desc_y.desc, desc_x.desc)
def coosort(x, sort_by='r'):
"""Sorts indices of COO-matrix in place.
Args:
x (cupyx.scipy.sparse.coo_matrix): A sparse matrix to sort.
sort_by (str): Sort the indices by row ('r', default) or column ('c').
"""
if not check_availability('coosort'):
raise RuntimeError('coosort is not available.')
nnz = x.nnz
if nnz == 0:
return
handle = _device.get_cusparse_handle()
m, n = x.shape
buffer_size = _cusparse.xcoosort_bufferSizeExt(
handle, m, n, nnz, x.row.data.ptr, x.col.data.ptr)
buf = _cupy.empty(buffer_size, 'b')
P = _cupy.empty(nnz, 'i')
data_orig = x.data.copy()
_cusparse.createIdentityPermutation(handle, nnz, P.data.ptr)
if sort_by == 'r':
_cusparse.xcoosortByRow(
handle, m, n, nnz, x.row.data.ptr, x.col.data.ptr,
P.data.ptr, buf.data.ptr)
elif sort_by == 'c':
_cusparse.xcoosortByColumn(
handle, m, n, nnz, x.row.data.ptr, x.col.data.ptr,
P.data.ptr, buf.data.ptr)
else:
raise ValueError("sort_by must be either 'r' or 'c'")
if check_availability('gthr'):
_call_cusparse(
'gthr', x.dtype,
handle, nnz, data_orig.data.ptr, x.data.data.ptr,
P.data.ptr, _cusparse.CUSPARSE_INDEX_BASE_ZERO)
else:
desc_x = SpVecDescriptor.create(P, x.data)
desc_y = DnVecDescriptor.create(data_orig)
_cusparse.gather(handle, desc_y.desc, desc_x.desc)
if sort_by == 'c': # coo is sorted by row first
x._has_canonical_format = False
def coo2csr(x):
handle = _device.get_cusparse_handle()
m = x.shape[0]
nnz = x.nnz
if nnz == 0:
indptr = _cupy.zeros(m 1, 'i')
else:
indptr = _cupy.empty(m 1, 'i')
_cusparse.xcoo2csr(
handle, x.row.data.ptr, nnz, m,
indptr.data.ptr, _cusparse.CUSPARSE_INDEX_BASE_ZERO)
return cupyx.scipy.sparse.csr_matrix(
(x.data, x.col, indptr), shape=x.shape)
def coo2csc(x):
handle = _device.get_cusparse_handle()
n = x.shape[1]
nnz = x.nnz
if nnz == 0:
indptr = _cupy.zeros(n 1, 'i')
else:
indptr = _cupy.empty(n 1, 'i')
_cusparse.xcoo2csr(
handle, x.col.data.ptr, nnz, n,
indptr.data.ptr, _cusparse.CUSPARSE_INDEX_BASE_ZERO)
return cupyx.scipy.sparse.csc_matrix(
(x.data, x.row, indptr), shape=x.shape)
def csr2coo(x, data, indices):
"""Converts a CSR-matrix to COO format.
Args:
x (cupyx.scipy.sparse.csr_matrix): A matrix to be converted.
data (cupy.ndarray): A data array for converted data.
indices (cupy.ndarray): An index array for converted data.
Returns:
cupyx.scipy.sparse.coo_matrix: A converted matrix.
"""
if not check_availability('csr2coo'):
raise RuntimeError('csr2coo is not available.')
handle = _device.get_cusparse_handle()
m = x.shape[0]