ZTWHHH commited on
Commit
252fbaf
·
verified ·
1 Parent(s): 5484651

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. vllm/lib/python3.10/site-packages/cupyx/__init__.py +33 -0
  2. vllm/lib/python3.10/site-packages/cupyx/_gufunc.py +5 -0
  3. vllm/lib/python3.10/site-packages/cupyx/_pinned_array.py +141 -0
  4. vllm/lib/python3.10/site-packages/cupyx/_rsqrt.py +7 -0
  5. vllm/lib/python3.10/site-packages/cupyx/_runtime.py +357 -0
  6. vllm/lib/python3.10/site-packages/cupyx/_scatter.py +131 -0
  7. vllm/lib/python3.10/site-packages/cupyx/_texture.py +197 -0
  8. vllm/lib/python3.10/site-packages/cupyx/_ufunc_config.py +123 -0
  9. vllm/lib/python3.10/site-packages/cupyx/cusparse.py +2093 -0
  10. vllm/lib/python3.10/site-packages/cupyx/fallback_mode/__init__.py +10 -0
  11. vllm/lib/python3.10/site-packages/cupyx/fallback_mode/__pycache__/__init__.cpython-310.pyc +0 -0
  12. vllm/lib/python3.10/site-packages/cupyx/fallback_mode/__pycache__/fallback.cpython-310.pyc +0 -0
  13. vllm/lib/python3.10/site-packages/cupyx/fallback_mode/__pycache__/notification.cpython-310.pyc +0 -0
  14. vllm/lib/python3.10/site-packages/cupyx/fallback_mode/fallback.py +596 -0
  15. vllm/lib/python3.10/site-packages/cupyx/fallback_mode/notification.py +75 -0
  16. vllm/lib/python3.10/site-packages/cupyx/lapack.py +348 -0
  17. vllm/lib/python3.10/site-packages/cupyx/optimizing/__init__.py +1 -0
  18. vllm/lib/python3.10/site-packages/cupyx/optimizing/__pycache__/__init__.cpython-310.pyc +0 -0
  19. vllm/lib/python3.10/site-packages/cupyx/optimizing/__pycache__/_optimize.cpython-310.pyc +0 -0
  20. vllm/lib/python3.10/site-packages/cupyx/optimizing/_optimize.py +109 -0
  21. vllm/lib/python3.10/site-packages/cupyx/profiler/__init__.py +31 -0
  22. vllm/lib/python3.10/site-packages/cupyx/profiler/__pycache__/__init__.cpython-310.pyc +0 -0
  23. vllm/lib/python3.10/site-packages/cupyx/profiler/__pycache__/_time.cpython-310.pyc +0 -0
  24. vllm/lib/python3.10/site-packages/cupyx/profiler/__pycache__/_time_range.cpython-310.pyc +0 -0
  25. vllm/lib/python3.10/site-packages/cupyx/profiler/_time.py +227 -0
  26. vllm/lib/python3.10/site-packages/cupyx/profiler/_time_range.py +89 -0
  27. vllm/lib/python3.10/site-packages/cupyx/signal/__init__.py +13 -0
  28. vllm/lib/python3.10/site-packages/cupyx/signal/_convolution/__init__.py +2 -0
  29. vllm/lib/python3.10/site-packages/cupyx/signal/_convolution/_convolve.py +223 -0
  30. vllm/lib/python3.10/site-packages/cupyx/signal/_radartools/__init__.py +5 -0
  31. vllm/lib/python3.10/site-packages/cupyx/signal/_radartools/__pycache__/__init__.cpython-310.pyc +0 -0
  32. vllm/lib/python3.10/site-packages/cupyx/signal/_radartools/__pycache__/_beamformers.cpython-310.pyc +0 -0
  33. vllm/lib/python3.10/site-packages/cupyx/signal/_radartools/__pycache__/_radartools.cpython-310.pyc +0 -0
  34. vllm/lib/python3.10/site-packages/cupyx/signal/_radartools/_beamformers.py +60 -0
  35. vllm/lib/python3.10/site-packages/cupyx/signal/_radartools/_radartools.py +309 -0
  36. vllm/lib/python3.10/site-packages/cupyx/time.py +90 -0
  37. vllm/lib/python3.10/site-packages/fsspec/__pycache__/__init__.cpython-310.pyc +0 -0
  38. vllm/lib/python3.10/site-packages/fsspec/__pycache__/_version.cpython-310.pyc +0 -0
  39. vllm/lib/python3.10/site-packages/fsspec/__pycache__/archive.cpython-310.pyc +0 -0
  40. vllm/lib/python3.10/site-packages/fsspec/__pycache__/asyn.cpython-310.pyc +0 -0
  41. vllm/lib/python3.10/site-packages/fsspec/__pycache__/caching.cpython-310.pyc +0 -0
  42. vllm/lib/python3.10/site-packages/fsspec/__pycache__/callbacks.cpython-310.pyc +0 -0
  43. vllm/lib/python3.10/site-packages/fsspec/__pycache__/compression.cpython-310.pyc +0 -0
  44. vllm/lib/python3.10/site-packages/fsspec/__pycache__/config.cpython-310.pyc +0 -0
  45. vllm/lib/python3.10/site-packages/fsspec/__pycache__/conftest.cpython-310.pyc +0 -0
  46. vllm/lib/python3.10/site-packages/fsspec/__pycache__/core.cpython-310.pyc +0 -0
  47. vllm/lib/python3.10/site-packages/fsspec/__pycache__/dircache.cpython-310.pyc +0 -0
  48. vllm/lib/python3.10/site-packages/fsspec/__pycache__/fuse.cpython-310.pyc +0 -0
  49. vllm/lib/python3.10/site-packages/fsspec/__pycache__/generic.cpython-310.pyc +0 -0
  50. vllm/lib/python3.10/site-packages/fsspec/__pycache__/gui.cpython-310.pyc +0 -0
vllm/lib/python3.10/site-packages/cupyx/__init__.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # "NOQA" to suppress flake8 warning
2
+ from cupyx._rsqrt import rsqrt # NOQA
3
+ from cupyx._runtime import get_runtime_info # NOQA
4
+ from cupyx._scatter import scatter_add # NOQA
5
+ from cupyx._scatter import scatter_max # NOQA
6
+ from cupyx._scatter import scatter_min # NOQA
7
+
8
+ from cupyx import linalg # NOQA
9
+ from cupyx import time # NOQA
10
+ from cupyx import scipy # NOQA
11
+ from cupyx import optimizing # NOQA
12
+
13
+ from cupyx._ufunc_config import errstate # NOQA
14
+ from cupyx._ufunc_config import geterr # NOQA
15
+ from cupyx._ufunc_config import seterr # NOQA
16
+ from cupy._core.syncdetect import allow_synchronize # NOQA
17
+ from cupy._core.syncdetect import DeviceSynchronized # NOQA
18
+
19
+ from cupyx._pinned_array import empty_pinned # NOQA
20
+ from cupyx._pinned_array import empty_like_pinned # NOQA
21
+ from cupyx._pinned_array import zeros_pinned # NOQA
22
+ from cupyx._pinned_array import zeros_like_pinned # NOQA
23
+
24
+ from cupyx._gufunc import GeneralizedUFunc # NOQA
25
+
26
+
27
+ def __getattr__(key):
28
+ if key == 'lapack':
29
+ import cupyx.lapack
30
+ return cupyx.lapack
31
+
32
+ raise AttributeError(
33
+ "module '{}' has no attribute '{}'".format(__name__, key))
vllm/lib/python3.10/site-packages/cupyx/_gufunc.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import cupy
2
+
3
+
4
+ class GeneralizedUFunc(cupy._core._gufuncs._GUFunc):
5
+ __doc__ = cupy._core._gufuncs._GUFunc.__doc__
vllm/lib/python3.10/site-packages/cupyx/_pinned_array.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy
2
+
3
+ from cupy import cuda
4
+ from cupy._creation.basic import _new_like_order_and_strides
5
+ from cupy._core import internal
6
+
7
+
8
+ def _update_shape(a, shape):
9
+ if shape is None and a is not None:
10
+ shape = a.shape
11
+ elif isinstance(shape, int):
12
+ shape = (shape,)
13
+ else:
14
+ shape = tuple(shape)
15
+ return shape
16
+
17
+
18
+ def empty_pinned(shape, dtype=float, order='C'):
19
+ """Returns a new, uninitialized NumPy array with the given shape
20
+ and dtype.
21
+
22
+ This is a convenience function which is just :func:`numpy.empty`,
23
+ except that the underlying memory is pinned/pagelocked.
24
+
25
+ Args:
26
+ shape (int or tuple of ints): Dimensionalities of the array.
27
+ dtype: Data type specifier.
28
+ order ({'C', 'F'}): Row-major (C-style) or column-major
29
+ (Fortran-style) order.
30
+
31
+ Returns:
32
+ numpy.ndarray: A new array with elements not initialized.
33
+
34
+ .. seealso:: :func:`numpy.empty`
35
+
36
+ """
37
+ shape = _update_shape(None, shape)
38
+ nbytes = internal.prod(shape) * numpy.dtype(dtype).itemsize
39
+ mem = cuda.alloc_pinned_memory(nbytes)
40
+ out = numpy.ndarray(shape, dtype=dtype, buffer=mem, order=order)
41
+ return out
42
+
43
+
44
+ def empty_like_pinned(a, dtype=None, order='K', subok=None, shape=None):
45
+ """Returns a new, uninitialized NumPy array with the same shape and dtype
46
+ as those of the given array.
47
+
48
+ This is a convenience function which is just :func:`numpy.empty_like`,
49
+ except that the underlying memory is pinned/pagelocked.
50
+
51
+ This function currently does not support ``subok`` option.
52
+
53
+ Args:
54
+ a (numpy.ndarray or cupy.ndarray): Base array.
55
+ dtype: Data type specifier. The data type of ``a`` is used by default.
56
+ order ({'C', 'F', 'A', or 'K'}): Overrides the memory layout of the
57
+ result. ``'C'`` means C-order, ``'F'`` means F-order, ``'A'`` means
58
+ ``'F'`` if ``a`` is Fortran contiguous, ``'C'`` otherwise.
59
+ ``'K'`` means match the layout of ``a`` as closely as possible.
60
+ subok: Not supported yet, must be None.
61
+ shape (int or tuple of ints): Overrides the shape of the result. If
62
+ ``order='K'`` and the number of dimensions is unchanged, will try
63
+ to keep order, otherwise, ``order='C'`` is implied.
64
+
65
+ Returns:
66
+ numpy.ndarray: A new array with same shape and dtype of ``a`` with
67
+ elements not initialized.
68
+
69
+ .. seealso:: :func:`numpy.empty_like`
70
+
71
+ """
72
+ # We're kinda duplicating the code here because order='K' needs special
73
+ # treatment: strides need to be computed
74
+ if subok is not None:
75
+ raise TypeError('subok is not supported yet')
76
+ if dtype is None:
77
+ dtype = a.dtype
78
+ shape = _update_shape(a, shape)
79
+ order, strides, _ = _new_like_order_and_strides(
80
+ a, dtype, order, shape, get_memptr=False)
81
+ nbytes = internal.prod(shape) * numpy.dtype(dtype).itemsize
82
+ mem = cuda.alloc_pinned_memory(nbytes)
83
+ out = numpy.ndarray(shape, dtype=dtype, buffer=mem,
84
+ strides=strides, order=order)
85
+ return out
86
+
87
+
88
+ def zeros_pinned(shape, dtype=float, order='C'):
89
+ """Returns a new, zero-initialized NumPy array with the given shape
90
+ and dtype.
91
+
92
+ This is a convenience function which is just :func:`numpy.zeros`,
93
+ except that the underlying memory is pinned/pagelocked.
94
+
95
+ Args:
96
+ shape (int or tuple of ints): Dimensionalities of the array.
97
+ dtype: Data type specifier.
98
+ order ({'C', 'F'}): Row-major (C-style) or column-major
99
+ (Fortran-style) order.
100
+
101
+ Returns:
102
+ numpy.ndarray: An array filled with zeros.
103
+
104
+ .. seealso:: :func:`numpy.zeros`
105
+
106
+ """
107
+ out = empty_pinned(shape, dtype, order)
108
+ numpy.copyto(out, 0, casting='unsafe')
109
+ return out
110
+
111
+
112
+ def zeros_like_pinned(a, dtype=None, order='K', subok=None, shape=None):
113
+ """Returns a new, zero-initialized NumPy array with the same shape and dtype
114
+ as those of the given array.
115
+
116
+ This is a convenience function which is just :func:`numpy.zeros_like`,
117
+ except that the underlying memory is pinned/pagelocked.
118
+
119
+ This function currently does not support ``subok`` option.
120
+
121
+ Args:
122
+ a (numpy.ndarray or cupy.ndarray): Base array.
123
+ dtype: Data type specifier. The dtype of ``a`` is used by default.
124
+ order ({'C', 'F', 'A', or 'K'}): Overrides the memory layout of the
125
+ result. ``'C'`` means C-order, ``'F'`` means F-order, ``'A'`` means
126
+ ``'F'`` if ``a`` is Fortran contiguous, ``'C'`` otherwise.
127
+ ``'K'`` means match the layout of ``a`` as closely as possible.
128
+ subok: Not supported yet, must be None.
129
+ shape (int or tuple of ints): Overrides the shape of the result. If
130
+ ``order='K'`` and the number of dimensions is unchanged, will try
131
+ to keep order, otherwise, ``order='C'`` is implied.
132
+
133
+ Returns:
134
+ numpy.ndarray: An array filled with zeros.
135
+
136
+ .. seealso:: :func:`numpy.zeros_like`
137
+
138
+ """ # NOQA
139
+ out = empty_like_pinned(a, dtype, order, subok, shape)
140
+ numpy.copyto(out, 0, casting='unsafe')
141
+ return out
vllm/lib/python3.10/site-packages/cupyx/_rsqrt.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from cupy._core.core import create_ufunc
2
+
3
+ rsqrt = create_ufunc(
4
+ 'cupy_rsqrt',
5
+ ('e->e', 'f->f', 'd->d', 'F->F', 'D->D'),
6
+ 'out0 = rsqrt(in0)',
7
+ doc='''Returns the reciprocal square root.''')
vllm/lib/python3.10/site-packages/cupyx/_runtime.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import io
3
+ import os
4
+ import platform
5
+ import warnings
6
+
7
+ import numpy
8
+
9
+ import cupy
10
+ import cupy_backends
11
+
12
+
13
+ is_hip = cupy_backends.cuda.api.runtime.is_hip
14
+
15
+
16
+ def _eval_or_error(func, errors):
17
+ # Evaluates `func` and return the result.
18
+ # If an error specified by `errors` occurred, it returns a string
19
+ # representing the error.
20
+ try:
21
+ return func()
22
+ except errors as e:
23
+ return repr(e)
24
+
25
+
26
+ class _InstallInfo(object):
27
+
28
+ # TODO(niboshi): Add is_binary_distribution
29
+
30
+ def __init__(self):
31
+ cupy_package_root = self._get_cupy_package_root()
32
+ if cupy_package_root is not None:
33
+ data_root = os.path.join(cupy_package_root, '.data')
34
+ data_paths = {
35
+ 'lib': _dir_or_none(os.path.join(data_root, 'lib')),
36
+ 'include': _dir_or_none(os.path.join(data_root, 'include')),
37
+ }
38
+ else:
39
+ data_paths = {
40
+ 'lib': None,
41
+ 'include': None,
42
+ }
43
+
44
+ self.cupy_package_root = cupy_package_root
45
+ self.data_paths = data_paths
46
+
47
+ def get_data_path(self, data_type):
48
+ if data_type not in self.data_paths:
49
+ raise ValueError('Invalid data type: {}'.format(data_type))
50
+ return self.data_paths[data_type]
51
+
52
+ def _get_cupy_package_root(self):
53
+ try:
54
+ cupy_path = inspect.getfile(cupy)
55
+ except TypeError:
56
+ return None
57
+ return os.path.dirname(cupy_path)
58
+
59
+
60
+ class _RuntimeInfo:
61
+
62
+ cupy_version = None
63
+ cuda_path = None
64
+
65
+ # CUDA Driver
66
+ cuda_build_version = None
67
+ cuda_driver_version = None
68
+
69
+ # CUDA Runtime
70
+ cuda_runtime_version = None
71
+ cuda_local_runtime_version = None
72
+
73
+ # CUDA Toolkit
74
+ cublas_version = None
75
+ cufft_version = None
76
+ curand_version = None
77
+ cusolver_version = None
78
+ cusparse_version = None
79
+ nvrtc_version = None
80
+ thrust_version = None
81
+ cuda_extra_include_dirs = None
82
+
83
+ # Optional Libraries
84
+ cudnn_build_version = None
85
+ cudnn_version = None
86
+ nccl_build_version = None
87
+ nccl_runtime_version = None
88
+ cub_build_version = None
89
+ jitify_build_version = None
90
+ cutensor_version = None
91
+ cusparselt_version = None
92
+ cython_build_version = None
93
+ cython_version = None
94
+
95
+ numpy_version = None
96
+ scipy_version = None
97
+
98
+ def __init__(self, *, full=True):
99
+ self.cupy_version = cupy.__version__
100
+
101
+ if not is_hip:
102
+ self.cuda_path = cupy.cuda.get_cuda_path()
103
+ else:
104
+ self.cuda_path = cupy._environment.get_rocm_path()
105
+
106
+ if not is_hip:
107
+ self.nvcc_path = cupy._environment.get_nvcc_path()
108
+ else:
109
+ self.nvcc_path = cupy._environment.get_hipcc_path()
110
+
111
+ # CUDA Driver
112
+ self.cuda_build_version = str(cupy.cuda.driver.get_build_version())
113
+ if cupy.cuda.driver._is_cuda_python():
114
+ try:
115
+ import cuda.bindings
116
+ cuda_version = cuda.bindings.__version__
117
+ except ImportError:
118
+ import cuda
119
+ cuda_version = cuda.__version__
120
+ self.cuda_build_version += f' (CUDA Python: {cuda_version})'
121
+ self.cuda_driver_version = _eval_or_error(
122
+ cupy.cuda.runtime.driverGetVersion,
123
+ cupy.cuda.runtime.CUDARuntimeError)
124
+
125
+ # CUDA Runtime
126
+ self.cuda_runtime_version = _eval_or_error(
127
+ cupy.cuda.runtime.runtimeGetVersion,
128
+ cupy.cuda.runtime.CUDARuntimeError)
129
+ self.cuda_local_runtime_version = _eval_or_error(
130
+ cupy.cuda.get_local_runtime_version,
131
+ Exception)
132
+
133
+ # cuBLAS
134
+ self.cublas_version = '(available)'
135
+ if full:
136
+ self.cublas_version = _eval_or_error(
137
+ lambda: cupy.cuda.cublas.getVersion(
138
+ cupy.cuda.device.get_cublas_handle()),
139
+ Exception)
140
+
141
+ # cuFFT
142
+ try:
143
+ from cupy.cuda import cufft
144
+ self.cufft_version = _eval_or_error(
145
+ lambda: cufft.getVersion(), Exception)
146
+ except ImportError:
147
+ pass
148
+
149
+ # cuRAND
150
+ self.curand_version = _eval_or_error(
151
+ lambda: cupy.cuda.curand.getVersion(),
152
+ Exception)
153
+
154
+ # cuSOLVER
155
+ self.cusolver_version = _eval_or_error(
156
+ lambda: cupy.cuda.cusolver._getVersion(),
157
+ Exception)
158
+
159
+ # cuSPARSE
160
+ self.cusparse_version = '(available)'
161
+ if full:
162
+ self.cusparse_version = _eval_or_error(
163
+ lambda: cupy.cuda.cusparse.getVersion(
164
+ cupy.cuda.device.get_cusparse_handle()),
165
+ Exception)
166
+
167
+ # NVRTC
168
+ self.nvrtc_version = _eval_or_error(
169
+ lambda: cupy.cuda.nvrtc.getVersion(),
170
+ Exception)
171
+
172
+ # Thrust
173
+ try:
174
+ import cupy.cuda.thrust as thrust
175
+ self.thrust_version = thrust.get_build_version()
176
+ except ImportError:
177
+ pass
178
+
179
+ # CUDA Extra Include Dirs
180
+ if not is_hip:
181
+ try:
182
+ nvrtc_version = cupy.cuda.nvrtc.getVersion()
183
+ except Exception:
184
+ nvrtc_version = None
185
+ if nvrtc_version is None:
186
+ self.cuda_extra_include_dirs = '(NVRTC unavailable)'
187
+ else:
188
+ self.cuda_extra_include_dirs = str(
189
+ cupy._environment._get_include_dir_from_conda_or_wheel(
190
+ *nvrtc_version))
191
+
192
+ # cuDNN
193
+ if cupy._environment._can_attempt_preload('cudnn'):
194
+ if full:
195
+ cupy._environment._preload_library('cudnn')
196
+ else:
197
+ self.cudnn_build_version = (
198
+ '(not loaded; try `import cupy.cuda.cudnn` first)')
199
+ self.cudnn_version = self.cudnn_build_version
200
+ try:
201
+ import cupy_backends.cuda.libs.cudnn as cudnn
202
+ self.cudnn_build_version = cudnn.get_build_version()
203
+ self.cudnn_version = _eval_or_error(
204
+ cudnn.getVersion, cudnn.CuDNNError)
205
+ except ImportError:
206
+ pass
207
+
208
+ # NCCL
209
+ if cupy._environment._can_attempt_preload('nccl'):
210
+ if full:
211
+ cupy._environment._preload_library('nccl')
212
+ else:
213
+ self.nccl_build_version = (
214
+ '(not loaded; try `import cupy.cuda.nccl` first)')
215
+ self.nccl_runtime_version = self.nccl_build_version
216
+ try:
217
+ import cupy_backends.cuda.libs.nccl as nccl
218
+ self.nccl_build_version = nccl.get_build_version()
219
+ nccl_runtime_version = nccl.get_version()
220
+ if nccl_runtime_version == 0:
221
+ nccl_runtime_version = '(unknown)'
222
+ self.nccl_runtime_version = nccl_runtime_version
223
+ except ImportError:
224
+ pass
225
+
226
+ # CUB
227
+ self.cub_build_version = cupy.cuda.cub.get_build_version()
228
+
229
+ try:
230
+ import cupy.cuda.jitify as jitify
231
+ self.jitify_build_version = jitify.get_build_version()
232
+ except ImportError:
233
+ pass
234
+
235
+ # cuTENSOR
236
+ try:
237
+ import cupy_backends.cuda.libs.cutensor as cutensor
238
+ self.cutensor_version = cutensor.get_version()
239
+ except ImportError:
240
+ pass
241
+
242
+ # cuSparseLT
243
+ try:
244
+ import cupy_backends.cuda.libs.cusparselt as cusparselt
245
+ self.cusparselt_version = cusparselt.get_build_version()
246
+ except ImportError:
247
+ pass
248
+
249
+ # Cython
250
+ self.cython_build_version = cupy._util.cython_build_ver
251
+ try:
252
+ import Cython
253
+ self.cython_version = Cython.__version__
254
+ except ImportError:
255
+ pass
256
+
257
+ # NumPy
258
+ self.numpy_version = numpy.version.full_version
259
+
260
+ # SciPy
261
+ try:
262
+ import scipy
263
+ self.scipy_version = scipy.version.full_version
264
+ except ImportError:
265
+ pass
266
+
267
+ def __str__(self):
268
+ records = [
269
+ ('OS', platform.platform()),
270
+ ('Python Version', platform.python_version()),
271
+ ('CuPy Version', self.cupy_version),
272
+ ('CuPy Platform', 'NVIDIA CUDA' if not is_hip else 'AMD ROCm'),
273
+ ('NumPy Version', self.numpy_version),
274
+ ('SciPy Version', self.scipy_version),
275
+ ('Cython Build Version', self.cython_build_version),
276
+ ('Cython Runtime Version', self.cython_version),
277
+ ('CUDA Root', self.cuda_path),
278
+ ('hipcc PATH' if is_hip else 'nvcc PATH', self.nvcc_path),
279
+
280
+ ('CUDA Build Version', self.cuda_build_version),
281
+ ('CUDA Driver Version', self.cuda_driver_version),
282
+
283
+ ('CUDA Runtime Version', (
284
+ f'{self.cuda_runtime_version} (linked to CuPy) / '
285
+ f'{self.cuda_local_runtime_version} (locally installed)'
286
+ )),
287
+ ('CUDA Extra Include Dirs', self.cuda_extra_include_dirs),
288
+ ]
289
+
290
+ records += [
291
+ ('cuBLAS Version', self.cublas_version),
292
+ ('cuFFT Version', self.cufft_version),
293
+ ('cuRAND Version', self.curand_version),
294
+ ('cuSOLVER Version', self.cusolver_version),
295
+ ('cuSPARSE Version', self.cusparse_version),
296
+ ('NVRTC Version', self.nvrtc_version),
297
+ ('Thrust Version', self.thrust_version),
298
+ ('CUB Build Version', self.cub_build_version),
299
+ ('Jitify Build Version', self.jitify_build_version),
300
+ ]
301
+
302
+ records += [
303
+ ('cuDNN Build Version', self.cudnn_build_version),
304
+ ('cuDNN Version', self.cudnn_version),
305
+ ('NCCL Build Version', self.nccl_build_version),
306
+ ('NCCL Runtime Version', self.nccl_runtime_version),
307
+ ('cuTENSOR Version', self.cutensor_version),
308
+ ('cuSPARSELt Build Version', self.cusparselt_version),
309
+ ]
310
+
311
+ device_count = 0
312
+ try:
313
+ device_count = cupy.cuda.runtime.getDeviceCount()
314
+ except cupy.cuda.runtime.CUDARuntimeError as e:
315
+ if 'ErrorNoDevice' not in e.args[0]:
316
+ warnings.warn(f'Failed to detect number of GPUs: {e}')
317
+ # No GPU devices available.
318
+ for device_id in range(device_count):
319
+ with cupy.cuda.Device(device_id) as device:
320
+ props = cupy.cuda.runtime.getDeviceProperties(device_id)
321
+ name = ('Device {} Name'.format(device_id),
322
+ props['name'].decode())
323
+ pci_bus = ('Device {} PCI Bus ID'.format(device_id),
324
+ device.pci_bus_id)
325
+ if is_hip:
326
+ try:
327
+ arch = props['gcnArchName'].decode()
328
+ except KeyError: # ROCm < 3.6.0
329
+ arch = 'gfx'+str(props['gcnArch'])
330
+ arch = ('Device {} Arch'.format(device_id), arch)
331
+ else:
332
+ arch = ('Device {} Compute Capability'.format(device_id),
333
+ device.compute_capability)
334
+ records += [name, arch, pci_bus]
335
+
336
+ width = max([len(r[0]) for r in records]) + 2
337
+ fmt = '{:' + str(width) + '}: {}\n'
338
+ s = io.StringIO()
339
+ for k, v in records:
340
+ s.write(fmt.format(k, v))
341
+
342
+ return s.getvalue()
343
+
344
+
345
+ def get_runtime_info(*, full=True):
346
+ return _RuntimeInfo(full=full)
347
+
348
+
349
+ def get_install_info():
350
+ return _InstallInfo()
351
+
352
+
353
+ def _dir_or_none(path):
354
+ """Returns None if path does not exist."""
355
+ if os.path.isdir(path):
356
+ return path
357
+ return None
vllm/lib/python3.10/site-packages/cupyx/_scatter.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def scatter_add(a, slices, value):
2
+ """Adds given values to specified elements of an array.
3
+
4
+ It adds ``value`` to the specified elements of ``a``.
5
+ If all of the indices target different locations, the operation of
6
+ :func:`scatter_add` is equivalent to ``a[slices] = a[slices] + value``.
7
+ If there are multiple elements targeting the same location,
8
+ :func:`scatter_add` uses all of these values for addition. On the other
9
+ hand, ``a[slices] = a[slices] + value`` only adds the contribution from one
10
+ of the indices targeting the same location.
11
+
12
+ Note that just like an array indexing, negative indices are interpreted as
13
+ counting from the end of an array.
14
+
15
+ Also note that :func:`scatter_add` behaves identically
16
+ to :func:`numpy.add.at`.
17
+
18
+ Example
19
+ -------
20
+ >>> import cupy
21
+ >>> import cupyx
22
+ >>> a = cupy.zeros((6,), dtype=cupy.float32)
23
+ >>> i = cupy.array([1, 0, 1])
24
+ >>> v = cupy.array([1., 1., 1.])
25
+ >>> cupyx.scatter_add(a, i, v);
26
+ >>> a
27
+ array([1., 2., 0., 0., 0., 0.], dtype=float32)
28
+
29
+ Args:
30
+ a (ndarray): An array that gets added.
31
+ slices: It is integer, slices, ellipsis, numpy.newaxis,
32
+ integer array-like, boolean array-like or tuple of them.
33
+ It works for slices used for
34
+ :func:`cupy.ndarray.__getitem__` and
35
+ :func:`cupy.ndarray.__setitem__`.
36
+ v (array-like): Values to increment ``a`` at referenced locations.
37
+
38
+ .. note::
39
+ It only supports types that are supported by CUDA's atomicAdd when
40
+ an integer array is included in ``slices``.
41
+ The supported types are ``numpy.float32``, ``numpy.int32``,
42
+ ``numpy.uint32``, ``numpy.uint64`` and ``numpy.ulonglong``.
43
+
44
+ .. note::
45
+ :func:`scatter_add` does not raise an error when indices exceed size of
46
+ axes. Instead, it wraps indices.
47
+
48
+ .. seealso:: :meth:`numpy.ufunc.at`.
49
+
50
+ """
51
+ a.scatter_add(slices, value)
52
+
53
+
54
+ def scatter_max(a, slices, value):
55
+ """Stores a maximum value of elements specified by indices to an array.
56
+
57
+ It stores the maximum value of elements in ``value`` array indexed by
58
+ ``slices`` to ``a``. If all of the indices target different locations,
59
+ the operation of :func:`scatter_max` is equivalent to
60
+ ``a[slices] = cupy.maximum(a[slices], value)``.
61
+ If there are multiple elements targeting the same location,
62
+ :func:`scatter_max` stores the maximum of all of these values to the given
63
+ index of ``a``, the initial element of ``a`` is also taken in account.
64
+
65
+ Note that just like an array indexing, negative indices are interpreted as
66
+ counting from the end of an array.
67
+
68
+ Also note that :func:`scatter_max` behaves identically
69
+ to :func:`numpy.maximum.at`.
70
+
71
+ Example
72
+ -------
73
+ >>> import numpy
74
+ >>> import cupy
75
+ >>> a = cupy.zeros((6,), dtype=numpy.float32)
76
+ >>> i = cupy.array([1, 0, 1, 2])
77
+ >>> v = cupy.array([1., 2., 3., -1.])
78
+ >>> cupyx.scatter_max(a, i, v);
79
+ >>> a
80
+ array([2., 3., 0., 0., 0., 0.], dtype=float32)
81
+
82
+ Args:
83
+ a (ndarray): An array to store the results.
84
+ slices: It is integer, slices, ellipsis, numpy.newaxis,
85
+ integer array-like, boolean array-like or tuple of them.
86
+ It works for slices used for
87
+ :func:`cupy.ndarray.__getitem__` and
88
+ :func:`cupy.ndarray.__setitem__`.
89
+ v (array-like): An array used for reference.
90
+ """
91
+ a.scatter_max(slices, value)
92
+
93
+
94
+ def scatter_min(a, slices, value):
95
+ """Stores a minimum value of elements specified by indices to an array.
96
+
97
+ It stores the minimum value of elements in ``value`` array indexed by
98
+ ``slices`` to ``a``. If all of the indices target different locations,
99
+ the operation of :func:`scatter_min` is equivalent to
100
+ ``a[slices] = cupy.minimum(a[slices], value)``.
101
+ If there are multiple elements targeting the same location,
102
+ :func:`scatter_min` stores the minimum of all of these values to the given
103
+ index of ``a``, the initial element of ``a`` is also taken in account.
104
+
105
+ Note that just like an array indexing, negative indices are interpreted as
106
+ counting from the end of an array.
107
+
108
+ Also note that :func:`scatter_min` behaves identically
109
+ to :func:`numpy.minimum.at`.
110
+
111
+ Example
112
+ -------
113
+ >>> import numpy
114
+ >>> import cupy
115
+ >>> a = cupy.zeros((6,), dtype=numpy.float32)
116
+ >>> i = cupy.array([1, 0, 1, 2])
117
+ >>> v = cupy.array([1., 2., 3., -1.])
118
+ >>> cupyx.scatter_min(a, i, v);
119
+ >>> a
120
+ array([ 0., 0., -1., 0., 0., 0.], dtype=float32)
121
+
122
+ Args:
123
+ a (ndarray): An array to store the results.
124
+ slices: It is integer, slices, ellipsis, numpy.newaxis,
125
+ integer array-like, boolean array-like or tuple of them.
126
+ It works for slices used for
127
+ :func:`cupy.ndarray.__getitem__` and
128
+ :func:`cupy.ndarray.__setitem__`.
129
+ v (array-like): An array used for reference.
130
+ """
131
+ a.scatter_min(slices, value)
vllm/lib/python3.10/site-packages/cupyx/_texture.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cupy
2
+
3
+ from cupy import _core
4
+ from cupy.cuda import texture
5
+ from cupy.cuda import runtime
6
+
7
+
8
+ _affine_transform_2d_array_kernel = _core.ElementwiseKernel(
9
+ 'U texObj, raw float32 m, uint64 width', 'T transformed_image',
10
+ '''
11
+ float3 pixel = make_float3(
12
+ (float)(i / width),
13
+ (float)(i % width),
14
+ 1.0f
15
+ );
16
+ float x = dot(pixel, make_float3(m[0], m[1], m[2])) + .5f;
17
+ float y = dot(pixel, make_float3(m[3], m[4], m[5])) + .5f;
18
+ transformed_image = tex2D<T>(texObj, y, x);
19
+ ''',
20
+ 'cupyx_texture_affine_transformation_2d_array',
21
+ preamble='''
22
+ inline __host__ __device__ float dot(float3 a, float3 b)
23
+ {
24
+ return a.x * b.x + a.y * b.y + a.z * b.z;
25
+ }
26
+ ''')
27
+
28
+
29
+ _affine_transform_3d_array_kernel = _core.ElementwiseKernel(
30
+ 'U texObj, raw float32 m, uint64 height, uint64 width',
31
+ 'T transformed_volume',
32
+ '''
33
+ float4 voxel = make_float4(
34
+ (float)(i / (width * height)),
35
+ (float)((i % (width * height)) / width),
36
+ (float)((i % (width * height)) % width),
37
+ 1.0f
38
+ );
39
+ float x = dot(voxel, make_float4(m[0], m[1], m[2], m[3])) + .5f;
40
+ float y = dot(voxel, make_float4(m[4], m[5], m[6], m[7])) + .5f;
41
+ float z = dot(voxel, make_float4(m[8], m[9], m[10], m[11])) + .5f;
42
+ transformed_volume = tex3D<T>(texObj, z, y, x);
43
+ ''',
44
+ 'cupyx_texture_affine_transformation_3d_array',
45
+ preamble='''
46
+ inline __host__ __device__ float dot(float4 a, float4 b)
47
+ {
48
+ return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
49
+ }
50
+ ''')
51
+
52
+
53
+ def _create_texture_object(data,
54
+ address_mode: str,
55
+ filter_mode: str,
56
+ read_mode: str,
57
+ border_color=0):
58
+
59
+ if cupy.issubdtype(data.dtype, cupy.unsignedinteger):
60
+ fmt_kind = runtime.cudaChannelFormatKindUnsigned
61
+ elif cupy.issubdtype(data.dtype, cupy.integer):
62
+ fmt_kind = runtime.cudaChannelFormatKindSigned
63
+ elif cupy.issubdtype(data.dtype, cupy.floating):
64
+ fmt_kind = runtime.cudaChannelFormatKindFloat
65
+ else:
66
+ raise ValueError(f'Unsupported data type {data.dtype}')
67
+
68
+ if address_mode == 'nearest':
69
+ address_mode = runtime.cudaAddressModeClamp
70
+ elif address_mode == 'constant':
71
+ address_mode = runtime.cudaAddressModeBorder
72
+ else:
73
+ raise ValueError(
74
+ f'Unsupported address mode {address_mode} '
75
+ '(supported: constant, nearest)')
76
+
77
+ if filter_mode == 'nearest':
78
+ filter_mode = runtime.cudaFilterModePoint
79
+ elif filter_mode == 'linear':
80
+ filter_mode = runtime.cudaFilterModeLinear
81
+ else:
82
+ raise ValueError(
83
+ f'Unsupported filter mode {filter_mode} '
84
+ f'(supported: nearest, linear)')
85
+
86
+ if read_mode == 'element_type':
87
+ read_mode = runtime.cudaReadModeElementType
88
+ elif read_mode == 'normalized_float':
89
+ read_mode = runtime.cudaReadModeNormalizedFloat
90
+ else:
91
+ raise ValueError(
92
+ f'Unsupported read mode {read_mode} '
93
+ '(supported: element_type, normalized_float)')
94
+
95
+ texture_fmt = texture.ChannelFormatDescriptor(
96
+ data.itemsize * 8, 0, 0, 0, fmt_kind)
97
+ # CUDAArray: last dimension is the fastest changing dimension
98
+ array = texture.CUDAarray(texture_fmt, *data.shape[::-1])
99
+ res_desc = texture.ResourceDescriptor(
100
+ runtime.cudaResourceTypeArray, cuArr=array)
101
+ # TODO(the-lay): each dimension can have a different addressing mode
102
+ # TODO(the-lay): border color/value can be defined for up to 4 channels
103
+ tex_desc = texture.TextureDescriptor(
104
+ (address_mode, ) * data.ndim, filter_mode, read_mode,
105
+ borderColors=(border_color, ))
106
+ tex_obj = texture.TextureObject(res_desc, tex_desc)
107
+ array.copy_from(data)
108
+
109
+ return tex_obj
110
+
111
+
112
+ def affine_transformation(data,
113
+ transformation_matrix,
114
+ output_shape=None,
115
+ output=None,
116
+ interpolation: str = 'linear',
117
+ mode: str = 'constant',
118
+ border_value=0):
119
+ """
120
+ Apply an affine transformation.
121
+
122
+ The method uses texture memory and supports only 2D and 3D float32 arrays
123
+ without channel dimension.
124
+
125
+ Args:
126
+ data (cupy.ndarray): The input array or texture object.
127
+ transformation_matrix (cupy.ndarray): Affine transformation matrix.
128
+ Must be a homogeneous and have shape ``(ndim + 1, ndim + 1)``.
129
+ output_shape (tuple of ints): Shape of output. If not specified,
130
+ the input array shape is used. Default is None.
131
+ output (cupy.ndarray or ~cupy.dtype): The array in which to place the
132
+ output, or the dtype of the returned array. If not specified,
133
+ creates the output array with shape of ``output_shape``. Default is
134
+ None.
135
+ interpolation (str): Specifies interpolation mode: ``'linear'`` or
136
+ ``'nearest'``. Default is ``'linear'``.
137
+ mode (str): Specifies addressing mode for points outside of the array:
138
+ (`'constant'``, ``'nearest'``). Default is ``'constant'``.
139
+ border_value: Specifies value to be used for coordinates outside
140
+ of the array for ``'constant'`` mode. Default is 0.
141
+
142
+ Returns:
143
+ cupy.ndarray:
144
+ The transformed input.
145
+
146
+ .. seealso:: :func:`cupyx.scipy.ndimage.affine_transform`
147
+ """
148
+
149
+ ndim = data.ndim
150
+ if (ndim < 2) or (ndim > 3):
151
+ raise ValueError(
152
+ 'Texture memory affine transformation is defined only for '
153
+ '2D and 3D arrays without channel dimension.')
154
+
155
+ dtype = data.dtype
156
+ if dtype != cupy.float32:
157
+ raise ValueError(f'Texture memory affine transformation is available '
158
+ f'only for float32 data type (not {dtype})')
159
+
160
+ if interpolation not in ['linear', 'nearest']:
161
+ raise ValueError(
162
+ f'Unsupported interpolation {interpolation} '
163
+ f'(supported: linear, nearest)')
164
+
165
+ if transformation_matrix.shape != (ndim + 1, ndim + 1):
166
+ raise ValueError('Matrix must be have shape (ndim + 1, ndim + 1)')
167
+
168
+ texture_object = _create_texture_object(data,
169
+ address_mode=mode,
170
+ filter_mode=interpolation,
171
+ read_mode='element_type',
172
+ border_color=border_value)
173
+
174
+ if ndim == 2:
175
+ kernel = _affine_transform_2d_array_kernel
176
+ else:
177
+ kernel = _affine_transform_3d_array_kernel
178
+
179
+ if output_shape is None:
180
+ output_shape = data.shape
181
+
182
+ if output is None:
183
+ output = cupy.zeros(output_shape, dtype=dtype)
184
+ elif isinstance(output, (type, cupy.dtype)):
185
+ if output != cupy.float32:
186
+ raise ValueError(f'Texture memory affine transformation is '
187
+ f'available only for float32 data type (not '
188
+ f'{output})')
189
+ output = cupy.zeros(output_shape, dtype=output)
190
+ elif isinstance(output, cupy.ndarray):
191
+ if output.shape != output_shape:
192
+ raise ValueError('Output shapes do not match')
193
+ else:
194
+ raise ValueError('Output must be None, cupy.ndarray or cupy.dtype')
195
+
196
+ kernel(texture_object, transformation_matrix, *output_shape[1:], output)
197
+ return output
vllm/lib/python3.10/site-packages/cupyx/_ufunc_config.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import threading
3
+
4
+
5
+ _config = threading.local()
6
+
7
+
8
+ def get_config_divide():
9
+ try:
10
+ value = _config.divide
11
+ except AttributeError:
12
+ value = _config.divide = None
13
+ return value
14
+
15
+
16
+ def get_config_over():
17
+ try:
18
+ value = _config.over
19
+ except AttributeError:
20
+ value = _config.over = None
21
+ return value
22
+
23
+
24
+ def get_config_under():
25
+ try:
26
+ value = _config.under
27
+ except AttributeError:
28
+ value = _config.under = None
29
+ return value
30
+
31
+
32
+ def get_config_invalid():
33
+ try:
34
+ value = _config.invalid
35
+ except AttributeError:
36
+ value = _config.invalid = None
37
+ return value
38
+
39
+
40
+ def get_config_linalg():
41
+ # In favor of performance, the `devInfo` input/output from cuSOLVER routine
42
+ # calls that is necessary to check the validity of the other outputs, are
43
+ # ignored, as D2H copy incurring device synchronizations would otherwise be
44
+ # required.
45
+ try:
46
+ value = _config.linalg
47
+ except AttributeError:
48
+ value = _config.linalg = 'ignore'
49
+ return value
50
+
51
+
52
+ def get_config_fallback_mode():
53
+ try:
54
+ value = _config.fallback_mode
55
+ except AttributeError:
56
+ value = _config.fallback_mode = 'ignore'
57
+ return value
58
+
59
+
60
+ @contextlib.contextmanager
61
+ def errstate(*, divide=None, over=None, under=None,
62
+ invalid=None, linalg=None, fallback_mode=None):
63
+ """
64
+ TODO(hvy): Write docs.
65
+ """
66
+ old_state = seterr(
67
+ divide=divide, over=over, under=under,
68
+ invalid=invalid, linalg=linalg, fallback_mode=fallback_mode)
69
+ try:
70
+ yield # Return `None` similar to `numpy.errstate`.
71
+ finally:
72
+ seterr(**old_state)
73
+
74
+
75
+ def seterr(*, divide=None, over=None, under=None,
76
+ invalid=None, linalg=None, fallback_mode=None):
77
+ """
78
+ TODO(hvy): Write docs.
79
+ """
80
+ old_state = geterr()
81
+
82
+ if divide is not None:
83
+ raise NotImplementedError()
84
+ if over is not None:
85
+ raise NotImplementedError()
86
+ if under is not None:
87
+ raise NotImplementedError()
88
+ if invalid is not None:
89
+ raise NotImplementedError()
90
+ if linalg is not None:
91
+ if linalg in ('ignore', 'raise'):
92
+ _config.linalg = linalg
93
+ else:
94
+ raise NotImplementedError()
95
+ if fallback_mode is not None:
96
+ if fallback_mode in ['print', 'warn', 'ignore', 'raise']:
97
+ _config.fallback_mode = fallback_mode
98
+ elif fallback_mode in ['log', 'call']:
99
+ raise NotImplementedError
100
+ else:
101
+ raise ValueError(
102
+ '{} is not a valid dispatch type'.format(fallback_mode))
103
+
104
+ _config.divide = divide
105
+ _config.under = under
106
+ _config.over = over
107
+ _config.invalid = invalid
108
+
109
+ return old_state
110
+
111
+
112
+ def geterr():
113
+ """
114
+ TODO(hvy): Write docs.
115
+ """
116
+ return dict(
117
+ divide=get_config_divide(),
118
+ over=get_config_over(),
119
+ under=get_config_under(),
120
+ invalid=get_config_invalid(),
121
+ linalg=get_config_linalg(),
122
+ fallback_mode=get_config_fallback_mode(),
123
+ )
vllm/lib/python3.10/site-packages/cupyx/cusparse.py ADDED
@@ -0,0 +1,2093 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools as _functools
2
+
3
+ import numpy as _numpy
4
+ import platform as _platform
5
+
6
+ import cupy as _cupy
7
+ from cupy_backends.cuda.api import driver as _driver
8
+ from cupy_backends.cuda.api import runtime as _runtime
9
+ from cupy_backends.cuda.libs import cusparse as _cusparse
10
+ from cupy._core import _dtype
11
+ from cupy.cuda import device as _device
12
+ from cupy.cuda import stream as _stream
13
+ from cupy import _util
14
+ import cupyx.scipy.sparse
15
+
16
+
17
+ class MatDescriptor(object):
18
+
19
+ def __init__(self, descriptor):
20
+ self.descriptor = descriptor
21
+
22
+ @classmethod
23
+ def create(cls):
24
+ descr = _cusparse.createMatDescr()
25
+ return MatDescriptor(descr)
26
+
27
+ def __reduce__(self):
28
+ return self.create, ()
29
+
30
+ def __del__(self, is_shutting_down=_util.is_shutting_down):
31
+ if is_shutting_down():
32
+ return
33
+ if self.descriptor:
34
+ _cusparse.destroyMatDescr(self.descriptor)
35
+ self.descriptor = None
36
+
37
+ def set_mat_type(self, typ):
38
+ _cusparse.setMatType(self.descriptor, typ)
39
+
40
+ def set_mat_index_base(self, base):
41
+ _cusparse.setMatIndexBase(self.descriptor, base)
42
+
43
+ def set_mat_fill_mode(self, fill_mode):
44
+ _cusparse.setMatFillMode(self.descriptor, fill_mode)
45
+
46
+ def set_mat_diag_type(self, diag_type):
47
+ _cusparse.setMatDiagType(self.descriptor, diag_type)
48
+
49
+
50
+ def _cast_common_type(*xs):
51
+ dtypes = [x.dtype for x in xs if x is not None]
52
+ dtype = _functools.reduce(_numpy.promote_types, dtypes)
53
+ return [x.astype(dtype) if x is not None and x.dtype != dtype else x
54
+ for x in xs]
55
+
56
+
57
+ def _transpose_flag(trans):
58
+ if trans:
59
+ return _cusparse.CUSPARSE_OPERATION_TRANSPOSE
60
+ else:
61
+ return _cusparse.CUSPARSE_OPERATION_NON_TRANSPOSE
62
+
63
+
64
+ def _call_cusparse(name, dtype, *args):
65
+ if dtype == 'f':
66
+ prefix = 's'
67
+ elif dtype == 'd':
68
+ prefix = 'd'
69
+ elif dtype == 'F':
70
+ prefix = 'c'
71
+ elif dtype == 'D':
72
+ prefix = 'z'
73
+ else:
74
+ raise TypeError
75
+ f = getattr(_cusparse, prefix + name)
76
+ return f(*args)
77
+
78
+
79
+ _available_cusparse_version = {
80
+ 'csrmv': (8000, 11000),
81
+ 'csrmvEx': (8000, 11000), # TODO(anaruse): failure in cuSparse 11.0
82
+ 'csrmm': (8000, 11000),
83
+ 'csrmm2': (8000, 11000),
84
+ 'csrgeam': (8000, 11000),
85
+ 'csrgeam2': (9020, None),
86
+ 'csrgemm': (8000, 11000),
87
+ 'csrgemm2': (8000, 12000),
88
+ 'gthr': (8000, 12000),
89
+
90
+ # Generic APIs are not available on CUDA 10.2 on Windows.
91
+ 'spmv': ({'Linux': 10200, 'Windows': 11000}, None),
92
+ # accuracy bugs in cuSparse 10.3.0
93
+ 'spmm': ({'Linux': 10301, 'Windows': 11000}, None),
94
+
95
+ 'csr2dense': (8000, 12000),
96
+ 'csc2dense': (8000, 12000),
97
+ 'csrsort': (8000, None),
98
+ 'cscsort': (8000, None),
99
+ 'coosort': (8000, None),
100
+ 'coo2csr': (8000, None),
101
+ 'csr2coo': (8000, None),
102
+ 'csr2csc': (8000, 11000),
103
+ 'csc2csr': (8000, 11000), # the entity is csr2csc
104
+ 'csr2cscEx2': (10200, None),
105
+ 'csc2csrEx2': (10200, None), # the entity is csr2cscEx2
106
+ 'dense2csc': (8000, None),
107
+ 'dense2csr': (8000, None),
108
+ 'csr2csr_compress': (8000, None),
109
+ 'csrsm2': (9020, 12000),
110
+ 'csrilu02': (8000, None),
111
+ 'denseToSparse': (11300, None),
112
+ 'sparseToDense': (11300, None),
113
+ 'spgemm': (11100, None),
114
+ 'spsm': (11600, None), # CUDA 11.3.1
115
+ }
116
+
117
+
118
+ _available_hipsparse_version = {
119
+ # For APIs supported by CUDA but not yet by HIP, we still need them here
120
+ # so that our test suite can cover both platforms.
121
+ 'csrmv': (305, None),
122
+ 'csrmvEx': (_numpy.inf, None),
123
+ 'csrmm': (305, None),
124
+ 'csrmm2': (305, None),
125
+ 'csrgeam': (305, None),
126
+ 'csrgeam2': (305, None),
127
+ 'csrgemm': (305, None),
128
+ 'csrgemm2': (305, None),
129
+ 'gthr': (305, None),
130
+ 'spmv': (402, None),
131
+ 'spmm': (402, None),
132
+ 'csr2dense': (305, None),
133
+ 'csc2dense': (305, None),
134
+ 'csrsort': (305, None),
135
+ 'cscsort': (305, None),
136
+ 'coosort': (305, None),
137
+ 'coo2csr': (305, None),
138
+ 'csr2coo': (305, None),
139
+ 'csr2csc': (305, None),
140
+ 'csc2csr': (305, None), # the entity is csr2csc
141
+ 'csr2cscEx2': (_numpy.inf, None),
142
+ 'csc2csrEx2': (_numpy.inf, None), # the entity is csr2cscEx2
143
+ 'dense2csc': (305, None),
144
+ 'dense2csr': (305, None),
145
+ 'csr2csr_compress': (305, None),
146
+ 'csrsm2': (305, None), # available since 305 but seems buggy
147
+ 'csrilu02': (305, None),
148
+ 'denseToSparse': (402, None),
149
+ 'sparseToDense': (402, None),
150
+ 'spgemm': (_numpy.inf, None),
151
+ 'spsm': (50000000, None),
152
+ }
153
+
154
+
155
+ def _get_avail_version_from_spec(x):
156
+ if isinstance(x, dict):
157
+ os_name = _platform.system()
158
+ if os_name not in x:
159
+ msg = 'No version information specified for the OS: {}'.format(
160
+ os_name)
161
+ raise ValueError(msg)
162
+ return x[os_name]
163
+ return x
164
+
165
+
166
+ @_util.memoize()
167
+ def check_availability(name):
168
+ if not _runtime.is_hip:
169
+ available_version = _available_cusparse_version
170
+ version = _cusparse.get_build_version()
171
+ else:
172
+ available_version = _available_hipsparse_version
173
+ version = _driver.get_build_version() # = HIP_VERSION
174
+ if name not in available_version:
175
+ msg = 'No available version information specified for {}'.format(name)
176
+ raise ValueError(msg)
177
+ version_added, version_removed = available_version[name]
178
+ version_added = _get_avail_version_from_spec(version_added)
179
+ version_removed = _get_avail_version_from_spec(version_removed)
180
+ if version_added is not None and version < version_added:
181
+ return False
182
+ if version_removed is not None and version >= version_removed:
183
+ return False
184
+ return True
185
+
186
+
187
+ def getVersion() -> int:
188
+ return _cusparse.getVersion(_device.get_cusparse_handle())
189
+
190
+
191
+ def csrmv(a, x, y=None, alpha=1, beta=0, transa=False):
192
+ """Matrix-vector product for a CSR-matrix and a dense vector.
193
+
194
+ .. math::
195
+
196
+ y = \\alpha * o_a(A) x + \\beta y,
197
+
198
+ where :math:`o_a` is a transpose function when ``transa`` is ``True`` and
199
+ is an identity function otherwise.
200
+
201
+ Args:
202
+ a (cupyx.cusparse.csr_matrix): Matrix A.
203
+ x (cupy.ndarray): Vector x.
204
+ y (cupy.ndarray or None): Vector y. It must be F-contiguous.
205
+ alpha (float): Coefficient for x.
206
+ beta (float): Coefficient for y.
207
+ transa (bool): If ``True``, transpose of ``A`` is used.
208
+
209
+ Returns:
210
+ cupy.ndarray: Calculated ``y``.
211
+
212
+ """
213
+ if not check_availability('csrmv'):
214
+ raise RuntimeError('csrmv is not available.')
215
+
216
+ assert y is None or y.flags.f_contiguous
217
+
218
+ a_shape = a.shape if not transa else a.shape[::-1]
219
+ if a_shape[1] != len(x):
220
+ raise ValueError('dimension mismatch')
221
+
222
+ handle = _device.get_cusparse_handle()
223
+ m, n = a_shape
224
+ a, x, y = _cast_common_type(a, x, y)
225
+ dtype = a.dtype
226
+ if y is None:
227
+ y = _cupy.zeros(m, dtype)
228
+ alpha = _numpy.array(alpha, dtype).ctypes
229
+ beta = _numpy.array(beta, dtype).ctypes
230
+
231
+ _call_cusparse(
232
+ 'csrmv', dtype,
233
+ handle, _transpose_flag(transa),
234
+ a.shape[0], a.shape[1], a.nnz, alpha.data, a._descr.descriptor,
235
+ a.data.data.ptr, a.indptr.data.ptr, a.indices.data.ptr,
236
+ x.data.ptr, beta.data, y.data.ptr)
237
+
238
+ return y
239
+
240
+
241
+ def csrmvExIsAligned(a, x, y=None):
242
+ """Check if the pointers of arguments for csrmvEx are aligned or not
243
+
244
+ Args:
245
+ a (cupyx.cusparse.csr_matrix): Matrix A.
246
+ x (cupy.ndarray): Vector x.
247
+ y (cupy.ndarray or None): Vector y.
248
+
249
+ Check if a, x, y pointers are aligned by 128 bytes as
250
+ required by csrmvEx.
251
+
252
+ Returns:
253
+ bool:
254
+ ``True`` if all pointers are aligned.
255
+ ``False`` if otherwise.
256
+
257
+ """
258
+
259
+ if a.data.data.ptr % 128 != 0:
260
+ return False
261
+ if a.indptr.data.ptr % 128 != 0:
262
+ return False
263
+ if a.indices.data.ptr % 128 != 0:
264
+ return False
265
+ if x.data.ptr % 128 != 0:
266
+ return False
267
+ if y is not None and y.data.ptr % 128 != 0:
268
+ return False
269
+ return True
270
+
271
+
272
+ def csrmvEx(a, x, y=None, alpha=1, beta=0, merge_path=True):
273
+ """Matrix-vector product for a CSR-matrix and a dense vector.
274
+
275
+ .. math::
276
+
277
+ y = \\alpha * A x + \\beta y,
278
+
279
+ Args:
280
+ a (cupyx.cusparse.csr_matrix): Matrix A.
281
+ x (cupy.ndarray): Vector x.
282
+ y (cupy.ndarray or None): Vector y. It must be F-contiguous.
283
+ alpha (float): Coefficient for x.
284
+ beta (float): Coefficient for y.
285
+ merge_path (bool): If ``True``, merge path algorithm is used.
286
+
287
+ All pointers must be aligned with 128 bytes.
288
+
289
+ Returns:
290
+ cupy.ndarray: Calculated ``y``.
291
+
292
+ """
293
+ if not check_availability('csrmvEx'):
294
+ raise RuntimeError('csrmvEx is not available.')
295
+
296
+ assert y is None or y.flags.f_contiguous
297
+
298
+ if a.shape[1] != len(x):
299
+ raise ValueError('dimension mismatch')
300
+
301
+ handle = _device.get_cusparse_handle()
302
+ m, n = a.shape
303
+
304
+ a, x, y = _cast_common_type(a, x, y)
305
+ dtype = a.dtype
306
+ if y is None:
307
+ y = _cupy.zeros(m, dtype)
308
+
309
+ datatype = _dtype.to_cuda_dtype(dtype)
310
+ algmode = _cusparse.CUSPARSE_ALG_MERGE_PATH if \
311
+ merge_path else _cusparse.CUSPARSE_ALG_NAIVE
312
+ transa_flag = _cusparse.CUSPARSE_OPERATION_NON_TRANSPOSE
313
+
314
+ alpha = _numpy.array(alpha, dtype).ctypes
315
+ beta = _numpy.array(beta, dtype).ctypes
316
+
317
+ assert csrmvExIsAligned(a, x, y)
318
+
319
+ bufferSize = _cusparse.csrmvEx_bufferSize(
320
+ handle, algmode, transa_flag,
321
+ a.shape[0], a.shape[1], a.nnz, alpha.data, datatype,
322
+ a._descr.descriptor, a.data.data.ptr, datatype,
323
+ a.indptr.data.ptr, a.indices.data.ptr,
324
+ x.data.ptr, datatype, beta.data, datatype,
325
+ y.data.ptr, datatype, datatype)
326
+
327
+ buf = _cupy.empty(bufferSize, 'b')
328
+ assert buf.data.ptr % 128 == 0
329
+
330
+ _cusparse.csrmvEx(
331
+ handle, algmode, transa_flag,
332
+ a.shape[0], a.shape[1], a.nnz, alpha.data, datatype,
333
+ a._descr.descriptor, a.data.data.ptr, datatype,
334
+ a.indptr.data.ptr, a.indices.data.ptr,
335
+ x.data.ptr, datatype, beta.data, datatype,
336
+ y.data.ptr, datatype, datatype, buf.data.ptr)
337
+ return y
338
+
339
+
340
+ def csrmm(a, b, c=None, alpha=1, beta=0, transa=False):
341
+ """Matrix-matrix product for a CSR-matrix and a dense matrix.
342
+
343
+ .. math::
344
+
345
+ C = \\alpha o_a(A) B + \\beta C,
346
+
347
+ where :math:`o_a` is a transpose function when ``transa`` is ``True`` and
348
+ is an identity function otherwise.
349
+
350
+ Args:
351
+ a (cupyx.scipy.sparse.csr): Sparse matrix A.
352
+ b (cupy.ndarray): Dense matrix B. It must be F-contiguous.
353
+ c (cupy.ndarray or None): Dense matrix C. It must be F-contiguous.
354
+ alpha (float): Coefficient for AB.
355
+ beta (float): Coefficient for C.
356
+ transa (bool): If ``True``, transpose of A is used.
357
+
358
+ Returns:
359
+ cupy.ndarray: Calculated C.
360
+
361
+ """
362
+ if not check_availability('csrmm'):
363
+ raise RuntimeError('csrmm is not available.')
364
+
365
+ assert a.ndim == b.ndim == 2
366
+ assert b.flags.f_contiguous
367
+ assert c is None or c.flags.f_contiguous
368
+
369
+ a_shape = a.shape if not transa else a.shape[::-1]
370
+ if a_shape[1] != b.shape[0]:
371
+ raise ValueError('dimension mismatch')
372
+
373
+ handle = _device.get_cusparse_handle()
374
+ m, k = a_shape
375
+ n = b.shape[1]
376
+
377
+ a, b, c = _cast_common_type(a, b, c)
378
+ if c is None:
379
+ c = _cupy.zeros((m, n), a.dtype, 'F')
380
+
381
+ ldb = k
382
+ ldc = m
383
+
384
+ alpha = _numpy.array(alpha, a.dtype).ctypes
385
+ beta = _numpy.array(beta, a.dtype).ctypes
386
+ _call_cusparse(
387
+ 'csrmm', a.dtype,
388
+ handle, _transpose_flag(transa),
389
+ a.shape[0], n, a.shape[1], a.nnz,
390
+ alpha.data, a._descr.descriptor, a.data.data.ptr,
391
+ a.indptr.data.ptr, a.indices.data.ptr,
392
+ b.data.ptr, ldb, beta.data, c.data.ptr, ldc)
393
+ return c
394
+
395
+
396
+ def csrmm2(a, b, c=None, alpha=1.0, beta=0.0, transa=False, transb=False):
397
+ """Matrix-matrix product for a CSR-matrix and a dense matrix.
398
+
399
+ .. math::
400
+
401
+ C = \\alpha o_a(A) o_b(B) + \\beta C,
402
+
403
+ where :math:`o_a` and :math:`o_b` are transpose functions when ``transa``
404
+ and ``tranb`` are ``True`` respectively. And they are identity functions
405
+ otherwise.
406
+ It is forbidden that both ``transa`` and ``transb`` are ``True`` in
407
+ cuSPARSE specification.
408
+
409
+ Args:
410
+ a (cupyx.scipy.sparse.csr): Sparse matrix A.
411
+ b (cupy.ndarray): Dense matrix B. It must be F-contiguous.
412
+ c (cupy.ndarray or None): Dense matrix C. It must be F-contiguous.
413
+ alpha (float): Coefficient for AB.
414
+ beta (float): Coefficient for C.
415
+ transa (bool): If ``True``, transpose of A is used.
416
+ transb (bool): If ``True``, transpose of B is used.
417
+
418
+ Returns:
419
+ cupy.ndarray: Calculated C.
420
+
421
+ """
422
+ if not check_availability('csrmm2'):
423
+ raise RuntimeError('csrmm2 is not available.')
424
+
425
+ assert a.ndim == b.ndim == 2
426
+ assert a.has_canonical_format
427
+ assert b.flags.f_contiguous
428
+ assert c is None or c.flags.f_contiguous
429
+ assert not (transa and transb)
430
+
431
+ a_shape = a.shape if not transa else a.shape[::-1]
432
+ b_shape = b.shape if not transb else b.shape[::-1]
433
+ if a_shape[1] != b_shape[0]:
434
+ raise ValueError('dimension mismatch')
435
+
436
+ handle = _device.get_cusparse_handle()
437
+ m, k = a_shape
438
+ n = b_shape[1]
439
+
440
+ a, b, c = _cast_common_type(a, b, c)
441
+ if c is None:
442
+ c = _cupy.zeros((m, n), a.dtype, 'F')
443
+
444
+ ldb = b.shape[0]
445
+ ldc = c.shape[0]
446
+ op_a = _transpose_flag(transa)
447
+ op_b = _transpose_flag(transb)
448
+ alpha = _numpy.array(alpha, a.dtype).ctypes
449
+ beta = _numpy.array(beta, a.dtype).ctypes
450
+ _call_cusparse(
451
+ 'csrmm2', a.dtype,
452
+ handle, op_a, op_b, a.shape[0], n, a.shape[1], a.nnz,
453
+ alpha.data, a._descr.descriptor, a.data.data.ptr,
454
+ a.indptr.data.ptr, a.indices.data.ptr,
455
+ b.data.ptr, ldb, beta.data, c.data.ptr, ldc)
456
+ return c
457
+
458
+
459
+ def csrgeam(a, b, alpha=1, beta=1):
460
+ """Matrix-matrix addition.
461
+
462
+ .. math::
463
+ C = \\alpha A + \\beta B
464
+
465
+ Args:
466
+ a (cupyx.scipy.sparse.csr_matrix): Sparse matrix A.
467
+ b (cupyx.scipy.sparse.csr_matrix): Sparse matrix B.
468
+ alpha (float): Coefficient for A.
469
+ beta (float): Coefficient for B.
470
+
471
+ Returns:
472
+ cupyx.scipy.sparse.csr_matrix: Result matrix.
473
+
474
+ """
475
+ if not check_availability('csrgeam'):
476
+ raise RuntimeError('csrgeam is not available.')
477
+
478
+ if not isinstance(a, cupyx.scipy.sparse.csr_matrix):
479
+ raise TypeError('unsupported type (actual: {})'.format(type(a)))
480
+ if not isinstance(b, cupyx.scipy.sparse.csr_matrix):
481
+ raise TypeError('unsupported type (actual: {})'.format(type(b)))
482
+ assert a.has_canonical_format
483
+ assert b.has_canonical_format
484
+ if a.shape != b.shape:
485
+ raise ValueError('inconsistent shapes')
486
+
487
+ handle = _device.get_cusparse_handle()
488
+ m, n = a.shape
489
+ a, b = _cast_common_type(a, b)
490
+ nnz = _numpy.empty((), 'i')
491
+ _cusparse.setPointerMode(
492
+ handle, _cusparse.CUSPARSE_POINTER_MODE_HOST)
493
+
494
+ c_descr = MatDescriptor.create()
495
+ c_indptr = _cupy.empty(m + 1, 'i')
496
+
497
+ _cusparse.xcsrgeamNnz(
498
+ handle, m, n,
499
+ a._descr.descriptor, a.nnz, a.indptr.data.ptr, a.indices.data.ptr,
500
+ b._descr.descriptor, b.nnz, b.indptr.data.ptr, b.indices.data.ptr,
501
+ c_descr.descriptor, c_indptr.data.ptr, nnz.ctypes.data)
502
+
503
+ c_indices = _cupy.empty(int(nnz), 'i')
504
+ c_data = _cupy.empty(int(nnz), a.dtype)
505
+ alpha = _numpy.array(alpha, a.dtype).ctypes
506
+ beta = _numpy.array(beta, a.dtype).ctypes
507
+ _call_cusparse(
508
+ 'csrgeam', a.dtype,
509
+ handle, m, n, alpha.data,
510
+ a._descr.descriptor, a.nnz, a.data.data.ptr,
511
+ a.indptr.data.ptr, a.indices.data.ptr, beta.data,
512
+ b._descr.descriptor, b.nnz, b.data.data.ptr,
513
+ b.indptr.data.ptr, b.indices.data.ptr,
514
+ c_descr.descriptor, c_data.data.ptr, c_indptr.data.ptr,
515
+ c_indices.data.ptr)
516
+
517
+ c = cupyx.scipy.sparse.csr_matrix(
518
+ (c_data, c_indices, c_indptr), shape=a.shape)
519
+ c._has_canonical_format = True
520
+ return c
521
+
522
+
523
+ def csrgeam2(a, b, alpha=1, beta=1):
524
+ """Matrix-matrix addition.
525
+
526
+ .. math::
527
+ C = \\alpha A + \\beta B
528
+
529
+ Args:
530
+ a (cupyx.scipy.sparse.csr_matrix): Sparse matrix A.
531
+ b (cupyx.scipy.sparse.csr_matrix): Sparse matrix B.
532
+ alpha (float): Coefficient for A.
533
+ beta (float): Coefficient for B.
534
+
535
+ Returns:
536
+ cupyx.scipy.sparse.csr_matrix: Result matrix.
537
+
538
+ """
539
+ if not check_availability('csrgeam2'):
540
+ raise RuntimeError('csrgeam2 is not available.')
541
+
542
+ if not isinstance(a, cupyx.scipy.sparse.csr_matrix):
543
+ raise TypeError('unsupported type (actual: {})'.format(type(a)))
544
+ if not isinstance(b, cupyx.scipy.sparse.csr_matrix):
545
+ raise TypeError('unsupported type (actual: {})'.format(type(b)))
546
+ assert a.has_canonical_format
547
+ assert b.has_canonical_format
548
+ if a.shape != b.shape:
549
+ raise ValueError('inconsistent shapes')
550
+
551
+ handle = _device.get_cusparse_handle()
552
+ m, n = a.shape
553
+ a, b = _cast_common_type(a, b)
554
+ nnz = _numpy.empty((), 'i')
555
+ _cusparse.setPointerMode(
556
+ handle, _cusparse.CUSPARSE_POINTER_MODE_HOST)
557
+
558
+ alpha = _numpy.array(alpha, a.dtype).ctypes
559
+ beta = _numpy.array(beta, a.dtype).ctypes
560
+ c_descr = MatDescriptor.create()
561
+ c_indptr = _cupy.empty(m + 1, 'i')
562
+
563
+ null_ptr = 0
564
+ buff_size = _call_cusparse(
565
+ 'csrgeam2_bufferSizeExt', a.dtype,
566
+ handle, m, n, alpha.data, a._descr.descriptor, a.nnz, a.data.data.ptr,
567
+ a.indptr.data.ptr, a.indices.data.ptr, beta.data, b._descr.descriptor,
568
+ b.nnz, b.data.data.ptr, b.indptr.data.ptr, b.indices.data.ptr,
569
+ c_descr.descriptor, null_ptr, c_indptr.data.ptr, null_ptr)
570
+ buff = _cupy.empty(buff_size, _numpy.int8)
571
+ _cusparse.xcsrgeam2Nnz(
572
+ handle, m, n, a._descr.descriptor, a.nnz, a.indptr.data.ptr,
573
+ a.indices.data.ptr, b._descr.descriptor, b.nnz, b.indptr.data.ptr,
574
+ b.indices.data.ptr, c_descr.descriptor, c_indptr.data.ptr,
575
+ nnz.ctypes.data, buff.data.ptr)
576
+ c_indices = _cupy.empty(int(nnz), 'i')
577
+ c_data = _cupy.empty(int(nnz), a.dtype)
578
+ _call_cusparse(
579
+ 'csrgeam2', a.dtype,
580
+ handle, m, n, alpha.data, a._descr.descriptor, a.nnz, a.data.data.ptr,
581
+ a.indptr.data.ptr, a.indices.data.ptr, beta.data, b._descr.descriptor,
582
+ b.nnz, b.data.data.ptr, b.indptr.data.ptr, b.indices.data.ptr,
583
+ c_descr.descriptor, c_data.data.ptr, c_indptr.data.ptr,
584
+ c_indices.data.ptr, buff.data.ptr)
585
+
586
+ c = cupyx.scipy.sparse.csr_matrix(
587
+ (c_data, c_indices, c_indptr), shape=a.shape)
588
+ c._has_canonical_format = True
589
+ return c
590
+
591
+
592
+ def csrgemm(a, b, transa=False, transb=False):
593
+ """Matrix-matrix product for CSR-matrix.
594
+
595
+ math::
596
+ C = op(A) op(B),
597
+
598
+ Args:
599
+ a (cupyx.scipy.sparse.csr_matrix): Sparse matrix A.
600
+ b (cupyx.scipy.sparse.csr_matrix): Sparse matrix B.
601
+ transa (bool): If ``True``, transpose of A is used.
602
+ transb (bool): If ``True``, transpose of B is used.
603
+
604
+ Returns:
605
+ cupyx.scipy.sparse.csr_matrix: Calculated C.
606
+
607
+ """
608
+ if not check_availability('csrgemm'):
609
+ raise RuntimeError('csrgemm is not available.')
610
+
611
+ assert a.ndim == b.ndim == 2
612
+ assert a.has_canonical_format
613
+ assert b.has_canonical_format
614
+ a_shape = a.shape if not transa else a.shape[::-1]
615
+ b_shape = b.shape if not transb else b.shape[::-1]
616
+ if a_shape[1] != b_shape[0]:
617
+ raise ValueError('dimension mismatch')
618
+
619
+ handle = _device.get_cusparse_handle()
620
+ m, k = a_shape
621
+ n = b_shape[1]
622
+
623
+ a, b = _cast_common_type(a, b)
624
+
625
+ if a.nnz == 0 or b.nnz == 0:
626
+ return cupyx.scipy.sparse.csr_matrix((m, n), dtype=a.dtype)
627
+
628
+ op_a = _transpose_flag(transa)
629
+ op_b = _transpose_flag(transb)
630
+
631
+ nnz = _numpy.empty((), 'i')
632
+ _cusparse.setPointerMode(
633
+ handle, _cusparse.CUSPARSE_POINTER_MODE_HOST)
634
+
635
+ c_descr = MatDescriptor.create()
636
+ c_indptr = _cupy.empty(m + 1, 'i')
637
+
638
+ _cusparse.xcsrgemmNnz(
639
+ handle, op_a, op_b, m, n, k, a._descr.descriptor, a.nnz,
640
+ a.indptr.data.ptr, a.indices.data.ptr, b._descr.descriptor, b.nnz,
641
+ b.indptr.data.ptr, b.indices.data.ptr, c_descr.descriptor,
642
+ c_indptr.data.ptr, nnz.ctypes.data)
643
+
644
+ c_indices = _cupy.empty(int(nnz), 'i')
645
+ c_data = _cupy.empty(int(nnz), a.dtype)
646
+ _call_cusparse(
647
+ 'csrgemm', a.dtype,
648
+ handle, op_a, op_b, m, n, k, a._descr.descriptor, a.nnz,
649
+ a.data.data.ptr, a.indptr.data.ptr, a.indices.data.ptr,
650
+ b._descr.descriptor, b.nnz, b.data.data.ptr, b.indptr.data.ptr,
651
+ b.indices.data.ptr,
652
+ c_descr.descriptor, c_data.data.ptr, c_indptr.data.ptr,
653
+ c_indices.data.ptr)
654
+
655
+ c = cupyx.scipy.sparse.csr_matrix(
656
+ (c_data, c_indices, c_indptr), shape=(m, n))
657
+ c._has_canonical_format = True
658
+ return c
659
+
660
+
661
+ def csrgemm2(a, b, d=None, alpha=1, beta=1):
662
+ """Matrix-matrix product for CSR-matrix.
663
+
664
+ math::
665
+ C = alpha * A * B + beta * D
666
+
667
+ Args:
668
+ a (cupyx.scipy.sparse.csr_matrix): Sparse matrix A.
669
+ b (cupyx.scipy.sparse.csr_matrix): Sparse matrix B.
670
+ d (cupyx.scipy.sparse.csr_matrix or None): Sparse matrix D.
671
+ alpha (scalar): Coefficient
672
+ beta (scalar): Coefficient
673
+
674
+ Returns:
675
+ cupyx.scipy.sparse.csr_matrix
676
+
677
+ """
678
+ if not check_availability('csrgemm2'):
679
+ raise RuntimeError('csrgemm2 is not available.')
680
+
681
+ assert a.ndim == b.ndim == 2
682
+ if not isinstance(a, cupyx.scipy.sparse.csr_matrix):
683
+ raise TypeError('unsupported type (actual: {})'.format(type(a)))
684
+ if not isinstance(b, cupyx.scipy.sparse.csr_matrix):
685
+ raise TypeError('unsupported type (actual: {})'.format(type(b)))
686
+ assert a.has_canonical_format
687
+ assert b.has_canonical_format
688
+ if a.shape[1] != b.shape[0]:
689
+ raise ValueError('mismatched shape')
690
+ if d is not None:
691
+ assert d.ndim == 2
692
+ if not isinstance(d, cupyx.scipy.sparse.csr_matrix):
693
+ raise TypeError('unsupported type (actual: {})'.format(type(d)))
694
+ assert d.has_canonical_format
695
+ if a.shape[0] != d.shape[0] or b.shape[1] != d.shape[1]:
696
+ raise ValueError('mismatched shape')
697
+ if _runtime.is_hip and _driver.get_build_version() < 402:
698
+ raise RuntimeError('d != None is supported since ROCm 4.2.0')
699
+
700
+ handle = _device.get_cusparse_handle()
701
+ m, k = a.shape
702
+ _, n = b.shape
703
+
704
+ if d is None:
705
+ a, b = _cast_common_type(a, b)
706
+ else:
707
+ a, b, d = _cast_common_type(a, b, d)
708
+
709
+ info = _cusparse.createCsrgemm2Info()
710
+ alpha = _numpy.array(alpha, a.dtype).ctypes
711
+ null_ptr = 0
712
+ if d is None:
713
+ beta_data = null_ptr
714
+ d_descr = MatDescriptor.create()
715
+ d_nnz = 0
716
+ d_data = null_ptr
717
+ d_indptr = null_ptr
718
+ d_indices = null_ptr
719
+ else:
720
+ beta = _numpy.array(beta, a.dtype).ctypes
721
+ beta_data = beta.data
722
+ d_descr = d._descr
723
+ d_nnz = d.nnz
724
+ d_data = d.data.data.ptr
725
+ d_indptr = d.indptr.data.ptr
726
+ d_indices = d.indices.data.ptr
727
+
728
+ buff_size = _call_cusparse(
729
+ 'csrgemm2_bufferSizeExt', a.dtype,
730
+ handle, m, n, k, alpha.data, a._descr.descriptor, a.nnz,
731
+ a.indptr.data.ptr, a.indices.data.ptr, b._descr.descriptor, b.nnz,
732
+ b.indptr.data.ptr, b.indices.data.ptr, beta_data, d_descr.descriptor,
733
+ d_nnz, d_indptr, d_indices, info)
734
+ buff = _cupy.empty(buff_size, _numpy.int8)
735
+
736
+ c_nnz = _numpy.empty((), 'i')
737
+ _cusparse.setPointerMode(handle, _cusparse.CUSPARSE_POINTER_MODE_HOST)
738
+
739
+ c_descr = MatDescriptor.create()
740
+ c_indptr = _cupy.empty(m + 1, 'i')
741
+ _cusparse.xcsrgemm2Nnz(
742
+ handle, m, n, k, a._descr.descriptor, a.nnz, a.indptr.data.ptr,
743
+ a.indices.data.ptr, b._descr.descriptor, b.nnz, b.indptr.data.ptr,
744
+ b.indices.data.ptr, d_descr.descriptor, d_nnz, d_indptr, d_indices,
745
+ c_descr.descriptor, c_indptr.data.ptr, c_nnz.ctypes.data, info,
746
+ buff.data.ptr)
747
+
748
+ c_indices = _cupy.empty(int(c_nnz), 'i')
749
+ c_data = _cupy.empty(int(c_nnz), a.dtype)
750
+ _call_cusparse(
751
+ 'csrgemm2', a.dtype,
752
+ handle, m, n, k, alpha.data, a._descr.descriptor, a.nnz,
753
+ a.data.data.ptr, a.indptr.data.ptr, a.indices.data.ptr,
754
+ b._descr.descriptor, b.nnz, b.data.data.ptr, b.indptr.data.ptr,
755
+ b.indices.data.ptr, beta_data, d_descr.descriptor, d_nnz, d_data,
756
+ d_indptr, d_indices, c_descr.descriptor, c_data.data.ptr,
757
+ c_indptr.data.ptr, c_indices.data.ptr, info, buff.data.ptr)
758
+
759
+ c = cupyx.scipy.sparse.csr_matrix(
760
+ (c_data, c_indices, c_indptr), shape=(m, n))
761
+ c._has_canonical_format = True
762
+ _cusparse.destroyCsrgemm2Info(info)
763
+ return c
764
+
765
+
766
+ def csr2dense(x, out=None):
767
+ """Converts CSR-matrix to a dense matrix.
768
+
769
+ Args:
770
+ x (cupyx.scipy.sparse.csr_matrix): A sparse matrix to convert.
771
+ out (cupy.ndarray or None): A dense metrix to store the result.
772
+ It must be F-contiguous.
773
+
774
+ Returns:
775
+ cupy.ndarray: Converted result.
776
+
777
+ """
778
+ if not check_availability('csr2dense'):
779
+ raise RuntimeError('csr2dense is not available.')
780
+
781
+ dtype = x.dtype
782
+ assert dtype.char in 'fdFD'
783
+ if out is None:
784
+ out = _cupy.empty(x.shape, dtype=dtype, order='F')
785
+ else:
786
+ assert out.flags.f_contiguous
787
+
788
+ handle = _device.get_cusparse_handle()
789
+ _call_cusparse(
790
+ 'csr2dense', x.dtype,
791
+ handle, x.shape[0], x.shape[1], x._descr.descriptor,
792
+ x.data.data.ptr, x.indptr.data.ptr, x.indices.data.ptr,
793
+ out.data.ptr, x.shape[0])
794
+
795
+ return out
796
+
797
+
798
+ def csc2dense(x, out=None):
799
+ """Converts CSC-matrix to a dense matrix.
800
+
801
+ Args:
802
+ x (cupyx.scipy.sparse.csc_matrix): A sparse matrix to convert.
803
+ out (cupy.ndarray or None): A dense metrix to store the result.
804
+ It must be F-contiguous.
805
+
806
+ Returns:
807
+ cupy.ndarray: Converted result.
808
+
809
+ """
810
+ if not check_availability('csc2dense'):
811
+ raise RuntimeError('csc2dense is not available.')
812
+
813
+ dtype = x.dtype
814
+ assert dtype.char in 'fdFD'
815
+ if out is None:
816
+ out = _cupy.empty(x.shape, dtype=dtype, order='F')
817
+ else:
818
+ assert out.flags.f_contiguous
819
+
820
+ handle = _device.get_cusparse_handle()
821
+ _call_cusparse(
822
+ 'csc2dense', x.dtype,
823
+ handle, x.shape[0], x.shape[1], x._descr.descriptor,
824
+ x.data.data.ptr, x.indices.data.ptr, x.indptr.data.ptr,
825
+ out.data.ptr, x.shape[0])
826
+
827
+ return out
828
+
829
+
830
+ def csrsort(x):
831
+ """Sorts indices of CSR-matrix in place.
832
+
833
+ Args:
834
+ x (cupyx.scipy.sparse.csr_matrix): A sparse matrix to sort.
835
+
836
+ """
837
+ if not check_availability('csrsort'):
838
+ raise RuntimeError('csrsort is not available.')
839
+
840
+ nnz = x.nnz
841
+ if nnz == 0:
842
+ return
843
+ handle = _device.get_cusparse_handle()
844
+ m, n = x.shape
845
+
846
+ buffer_size = _cusparse.xcsrsort_bufferSizeExt(
847
+ handle, m, n, nnz, x.indptr.data.ptr,
848
+ x.indices.data.ptr)
849
+ buf = _cupy.empty(buffer_size, 'b')
850
+ P = _cupy.empty(nnz, 'i')
851
+ data_orig = x.data.copy()
852
+ _cusparse.createIdentityPermutation(handle, nnz, P.data.ptr)
853
+ _cusparse.xcsrsort(
854
+ handle, m, n, nnz, x._descr.descriptor, x.indptr.data.ptr,
855
+ x.indices.data.ptr, P.data.ptr, buf.data.ptr)
856
+
857
+ if check_availability('gthr'):
858
+ _call_cusparse(
859
+ 'gthr', x.dtype,
860
+ handle, nnz, data_orig.data.ptr, x.data.data.ptr,
861
+ P.data.ptr, _cusparse.CUSPARSE_INDEX_BASE_ZERO)
862
+ else:
863
+ desc_x = SpVecDescriptor.create(P, x.data)
864
+ desc_y = DnVecDescriptor.create(data_orig)
865
+ _cusparse.gather(handle, desc_y.desc, desc_x.desc)
866
+
867
+
868
+ def cscsort(x):
869
+ """Sorts indices of CSC-matrix in place.
870
+
871
+ Args:
872
+ x (cupyx.scipy.sparse.csc_matrix): A sparse matrix to sort.
873
+
874
+ """
875
+ if not check_availability('cscsort'):
876
+ raise RuntimeError('cscsort is not available.')
877
+
878
+ nnz = x.nnz
879
+ if nnz == 0:
880
+ return
881
+ handle = _device.get_cusparse_handle()
882
+ m, n = x.shape
883
+
884
+ buffer_size = _cusparse.xcscsort_bufferSizeExt(
885
+ handle, m, n, nnz, x.indptr.data.ptr,
886
+ x.indices.data.ptr)
887
+ buf = _cupy.empty(buffer_size, 'b')
888
+ P = _cupy.empty(nnz, 'i')
889
+ data_orig = x.data.copy()
890
+ _cusparse.createIdentityPermutation(handle, nnz, P.data.ptr)
891
+ _cusparse.xcscsort(
892
+ handle, m, n, nnz, x._descr.descriptor, x.indptr.data.ptr,
893
+ x.indices.data.ptr, P.data.ptr, buf.data.ptr)
894
+
895
+ if check_availability('gthr'):
896
+ _call_cusparse(
897
+ 'gthr', x.dtype,
898
+ handle, nnz, data_orig.data.ptr, x.data.data.ptr,
899
+ P.data.ptr, _cusparse.CUSPARSE_INDEX_BASE_ZERO)
900
+ else:
901
+ desc_x = SpVecDescriptor.create(P, x.data)
902
+ desc_y = DnVecDescriptor.create(data_orig)
903
+ _cusparse.gather(handle, desc_y.desc, desc_x.desc)
904
+
905
+
906
+ def coosort(x, sort_by='r'):
907
+ """Sorts indices of COO-matrix in place.
908
+
909
+ Args:
910
+ x (cupyx.scipy.sparse.coo_matrix): A sparse matrix to sort.
911
+ sort_by (str): Sort the indices by row ('r', default) or column ('c').
912
+
913
+ """
914
+ if not check_availability('coosort'):
915
+ raise RuntimeError('coosort is not available.')
916
+
917
+ nnz = x.nnz
918
+ if nnz == 0:
919
+ return
920
+ handle = _device.get_cusparse_handle()
921
+ m, n = x.shape
922
+
923
+ buffer_size = _cusparse.xcoosort_bufferSizeExt(
924
+ handle, m, n, nnz, x.row.data.ptr, x.col.data.ptr)
925
+ buf = _cupy.empty(buffer_size, 'b')
926
+ P = _cupy.empty(nnz, 'i')
927
+ data_orig = x.data.copy()
928
+ _cusparse.createIdentityPermutation(handle, nnz, P.data.ptr)
929
+ if sort_by == 'r':
930
+ _cusparse.xcoosortByRow(
931
+ handle, m, n, nnz, x.row.data.ptr, x.col.data.ptr,
932
+ P.data.ptr, buf.data.ptr)
933
+ elif sort_by == 'c':
934
+ _cusparse.xcoosortByColumn(
935
+ handle, m, n, nnz, x.row.data.ptr, x.col.data.ptr,
936
+ P.data.ptr, buf.data.ptr)
937
+ else:
938
+ raise ValueError("sort_by must be either 'r' or 'c'")
939
+
940
+ if x.dtype.char != '?':
941
+ if check_availability('gthr'):
942
+ _call_cusparse(
943
+ 'gthr', x.dtype,
944
+ handle, nnz, data_orig.data.ptr, x.data.data.ptr,
945
+ P.data.ptr, _cusparse.CUSPARSE_INDEX_BASE_ZERO)
946
+ else:
947
+ desc_x = SpVecDescriptor.create(P, x.data)
948
+ desc_y = DnVecDescriptor.create(data_orig)
949
+ _cusparse.gather(handle, desc_y.desc, desc_x.desc)
950
+
951
+ if sort_by == 'c': # coo is sorted by row first
952
+ x._has_canonical_format = False
953
+
954
+
955
+ def coo2csr(x):
956
+ handle = _device.get_cusparse_handle()
957
+ m = x.shape[0]
958
+ nnz = x.nnz
959
+ if nnz == 0:
960
+ indptr = _cupy.zeros(m + 1, 'i')
961
+ else:
962
+ indptr = _cupy.empty(m + 1, 'i')
963
+ _cusparse.xcoo2csr(
964
+ handle, x.row.data.ptr, nnz, m,
965
+ indptr.data.ptr, _cusparse.CUSPARSE_INDEX_BASE_ZERO)
966
+ return cupyx.scipy.sparse.csr_matrix(
967
+ (x.data, x.col, indptr), shape=x.shape)
968
+
969
+
970
+ def coo2csc(x):
971
+ handle = _device.get_cusparse_handle()
972
+ n = x.shape[1]
973
+ nnz = x.nnz
974
+ if nnz == 0:
975
+ indptr = _cupy.zeros(n + 1, 'i')
976
+ else:
977
+ indptr = _cupy.empty(n + 1, 'i')
978
+ _cusparse.xcoo2csr(
979
+ handle, x.col.data.ptr, nnz, n,
980
+ indptr.data.ptr, _cusparse.CUSPARSE_INDEX_BASE_ZERO)
981
+ return cupyx.scipy.sparse.csc_matrix(
982
+ (x.data, x.row, indptr), shape=x.shape)
983
+
984
+
985
+ def csr2coo(x, data, indices):
986
+ """Converts a CSR-matrix to COO format.
987
+
988
+ Args:
989
+ x (cupyx.scipy.sparse.csr_matrix): A matrix to be converted.
990
+ data (cupy.ndarray): A data array for converted data.
991
+ indices (cupy.ndarray): An index array for converted data.
992
+
993
+ Returns:
994
+ cupyx.scipy.sparse.coo_matrix: A converted matrix.
995
+
996
+ """
997
+ if not check_availability('csr2coo'):
998
+ raise RuntimeError('csr2coo is not available.')
999
+
1000
+ handle = _device.get_cusparse_handle()
1001
+ m = x.shape[0]
1002
+ nnz = x.nnz
1003
+ row = _cupy.empty(nnz, 'i')
1004
+ _cusparse.xcsr2coo(
1005
+ handle, x.indptr.data.ptr, nnz, m, row.data.ptr,
1006
+ _cusparse.CUSPARSE_INDEX_BASE_ZERO)
1007
+ # data and indices did not need to be copied already
1008
+ return cupyx.scipy.sparse.coo_matrix(
1009
+ (data, (row, indices)), shape=x.shape)
1010
+
1011
+
1012
+ def csr2csc(x):
1013
+ if not check_availability('csr2csc'):
1014
+ raise RuntimeError('csr2csc is not available.')
1015
+
1016
+ handle = _device.get_cusparse_handle()
1017
+ m, n = x.shape
1018
+ nnz = x.nnz
1019
+ data = _cupy.empty(nnz, x.dtype)
1020
+ indices = _cupy.empty(nnz, 'i')
1021
+ if nnz == 0:
1022
+ indptr = _cupy.zeros(n + 1, 'i')
1023
+ else:
1024
+ indptr = _cupy.empty(n + 1, 'i')
1025
+ _call_cusparse(
1026
+ 'csr2csc', x.dtype,
1027
+ handle, m, n, nnz, x.data.data.ptr,
1028
+ x.indptr.data.ptr, x.indices.data.ptr,
1029
+ data.data.ptr, indices.data.ptr, indptr.data.ptr,
1030
+ _cusparse.CUSPARSE_ACTION_NUMERIC,
1031
+ _cusparse.CUSPARSE_INDEX_BASE_ZERO)
1032
+ return cupyx.scipy.sparse.csc_matrix(
1033
+ (data, indices, indptr), shape=x.shape)
1034
+
1035
+
1036
+ def csr2cscEx2(x):
1037
+ if not check_availability('csr2cscEx2'):
1038
+ raise RuntimeError('csr2cscEx2 is not available.')
1039
+
1040
+ handle = _device.get_cusparse_handle()
1041
+ m, n = x.shape
1042
+ nnz = x.nnz
1043
+ data = _cupy.empty(nnz, x.dtype)
1044
+ indices = _cupy.empty(nnz, 'i')
1045
+ if nnz == 0:
1046
+ indptr = _cupy.zeros(n + 1, 'i')
1047
+ else:
1048
+ indptr = _cupy.empty(n + 1, 'i')
1049
+ x_dtype = _dtype.to_cuda_dtype(x.dtype)
1050
+ action = _cusparse.CUSPARSE_ACTION_NUMERIC
1051
+ ibase = _cusparse.CUSPARSE_INDEX_BASE_ZERO
1052
+ algo = _cusparse.CUSPARSE_CSR2CSC_ALG1
1053
+ buffer_size = _cusparse.csr2cscEx2_bufferSize(
1054
+ handle, m, n, nnz, x.data.data.ptr, x.indptr.data.ptr,
1055
+ x.indices.data.ptr, data.data.ptr, indptr.data.ptr,
1056
+ indices.data.ptr, x_dtype, action, ibase, algo)
1057
+ buffer = _cupy.empty(buffer_size, _numpy.int8)
1058
+ _cusparse.csr2cscEx2(
1059
+ handle, m, n, nnz, x.data.data.ptr, x.indptr.data.ptr,
1060
+ x.indices.data.ptr, data.data.ptr, indptr.data.ptr,
1061
+ indices.data.ptr, x_dtype, action, ibase, algo, buffer.data.ptr)
1062
+ return cupyx.scipy.sparse.csc_matrix(
1063
+ (data, indices, indptr), shape=x.shape)
1064
+
1065
+
1066
+ def csc2coo(x, data, indices):
1067
+ """Converts a CSC-matrix to COO format.
1068
+
1069
+ Args:
1070
+ x (cupyx.scipy.sparse.csc_matrix): A matrix to be converted.
1071
+ data (cupy.ndarray): A data array for converted data.
1072
+ indices (cupy.ndarray): An index array for converted data.
1073
+
1074
+ Returns:
1075
+ cupyx.scipy.sparse.coo_matrix: A converted matrix.
1076
+
1077
+ """
1078
+ handle = _device.get_cusparse_handle()
1079
+ n = x.shape[1]
1080
+ nnz = x.nnz
1081
+ col = _cupy.empty(nnz, 'i')
1082
+ _cusparse.xcsr2coo(
1083
+ handle, x.indptr.data.ptr, nnz, n, col.data.ptr,
1084
+ _cusparse.CUSPARSE_INDEX_BASE_ZERO)
1085
+ # data and indices did not need to be copied already
1086
+ return cupyx.scipy.sparse.coo_matrix(
1087
+ (data, (indices, col)), shape=x.shape)
1088
+
1089
+
1090
+ def csc2csr(x):
1091
+ if not check_availability('csc2csr'):
1092
+ raise RuntimeError('csr2csc is not available.')
1093
+
1094
+ handle = _device.get_cusparse_handle()
1095
+ m, n = x.shape
1096
+ nnz = x.nnz
1097
+ data = _cupy.empty(nnz, x.dtype)
1098
+ indices = _cupy.empty(nnz, 'i')
1099
+ if nnz == 0:
1100
+ indptr = _cupy.zeros(m + 1, 'i')
1101
+ else:
1102
+ indptr = _cupy.empty(m + 1, 'i')
1103
+ _call_cusparse(
1104
+ 'csr2csc', x.dtype,
1105
+ handle, n, m, nnz, x.data.data.ptr,
1106
+ x.indptr.data.ptr, x.indices.data.ptr,
1107
+ data.data.ptr, indices.data.ptr, indptr.data.ptr,
1108
+ _cusparse.CUSPARSE_ACTION_NUMERIC,
1109
+ _cusparse.CUSPARSE_INDEX_BASE_ZERO)
1110
+ return cupyx.scipy.sparse.csr_matrix(
1111
+ (data, indices, indptr), shape=x.shape)
1112
+
1113
+
1114
+ def csc2csrEx2(x):
1115
+ if not check_availability('csc2csrEx2'):
1116
+ raise RuntimeError('csc2csrEx2 is not available.')
1117
+
1118
+ handle = _device.get_cusparse_handle()
1119
+ m, n = x.shape
1120
+ nnz = x.nnz
1121
+ data = _cupy.empty(nnz, x.dtype)
1122
+ indices = _cupy.empty(nnz, 'i')
1123
+ if nnz == 0:
1124
+ indptr = _cupy.zeros(m + 1, 'i')
1125
+ else:
1126
+ indptr = _cupy.empty(m + 1, 'i')
1127
+ x_dtype = _dtype.to_cuda_dtype(x.dtype)
1128
+ action = _cusparse.CUSPARSE_ACTION_NUMERIC
1129
+ ibase = _cusparse.CUSPARSE_INDEX_BASE_ZERO
1130
+ algo = _cusparse.CUSPARSE_CSR2CSC_ALG1
1131
+ buffer_size = _cusparse.csr2cscEx2_bufferSize(
1132
+ handle, n, m, nnz, x.data.data.ptr, x.indptr.data.ptr,
1133
+ x.indices.data.ptr, data.data.ptr, indptr.data.ptr,
1134
+ indices.data.ptr, x_dtype, action, ibase, algo)
1135
+ buffer = _cupy.empty(buffer_size, _numpy.int8)
1136
+ _cusparse.csr2cscEx2(
1137
+ handle, n, m, nnz, x.data.data.ptr, x.indptr.data.ptr,
1138
+ x.indices.data.ptr, data.data.ptr, indptr.data.ptr,
1139
+ indices.data.ptr, x_dtype, action, ibase, algo, buffer.data.ptr)
1140
+ return cupyx.scipy.sparse.csr_matrix(
1141
+ (data, indices, indptr), shape=x.shape)
1142
+
1143
+
1144
+ def dense2csc(x):
1145
+ """Converts a dense matrix in CSC format.
1146
+
1147
+ Args:
1148
+ x (cupy.ndarray): A matrix to be converted.
1149
+
1150
+ Returns:
1151
+ cupyx.scipy.sparse.csc_matrix: A converted matrix.
1152
+
1153
+ """
1154
+ if not check_availability('dense2csc'):
1155
+ raise RuntimeError('dense2csc is not available.')
1156
+
1157
+ assert x.ndim == 2
1158
+ x = _cupy.asfortranarray(x)
1159
+ nnz = _numpy.empty((), dtype='i')
1160
+ handle = _device.get_cusparse_handle()
1161
+ m, n = x.shape
1162
+
1163
+ descr = MatDescriptor.create()
1164
+ nnz_per_col = _cupy.empty(m, 'i')
1165
+ _call_cusparse(
1166
+ 'nnz', x.dtype,
1167
+ handle, _cusparse.CUSPARSE_DIRECTION_COLUMN, m, n, descr.descriptor,
1168
+ x.data.ptr, m, nnz_per_col.data.ptr, nnz.ctypes.data)
1169
+
1170
+ nnz = int(nnz)
1171
+ data = _cupy.empty(nnz, x.dtype)
1172
+ indptr = _cupy.empty(n + 1, 'i')
1173
+ indices = _cupy.empty(nnz, 'i')
1174
+
1175
+ _call_cusparse(
1176
+ 'dense2csc', x.dtype,
1177
+ handle, m, n, descr.descriptor,
1178
+ x.data.ptr, m, nnz_per_col.data.ptr,
1179
+ data.data.ptr, indices.data.ptr, indptr.data.ptr)
1180
+ # Note that a descriptor is recreated
1181
+ csc = cupyx.scipy.sparse.csc_matrix((data, indices, indptr), shape=x.shape)
1182
+ csc._has_canonical_format = True
1183
+ return csc
1184
+
1185
+
1186
+ def dense2csr(x):
1187
+ """Converts a dense matrix in CSR format.
1188
+
1189
+ Args:
1190
+ x (cupy.ndarray): A matrix to be converted.
1191
+
1192
+ Returns:
1193
+ cupyx.scipy.sparse.csr_matrix: A converted matrix.
1194
+
1195
+ """
1196
+ if not check_availability('dense2csr'):
1197
+ raise RuntimeError('dense2csr is not available.')
1198
+
1199
+ assert x.ndim == 2
1200
+ x = _cupy.asfortranarray(x)
1201
+ nnz = _numpy.empty((), dtype='i')
1202
+ handle = _device.get_cusparse_handle()
1203
+ m, n = x.shape
1204
+
1205
+ descr = MatDescriptor.create()
1206
+ nnz_per_row = _cupy.empty(m, 'i')
1207
+ _call_cusparse(
1208
+ 'nnz', x.dtype,
1209
+ handle, _cusparse.CUSPARSE_DIRECTION_ROW, m, n, descr.descriptor,
1210
+ x.data.ptr, m, nnz_per_row.data.ptr, nnz.ctypes.data)
1211
+
1212
+ nnz = int(nnz)
1213
+ if _runtime.is_hip:
1214
+ if nnz == 0:
1215
+ raise ValueError('hipSPARSE currently cannot handle '
1216
+ 'sparse matrices with null ptrs')
1217
+ data = _cupy.empty(nnz, x.dtype)
1218
+ indptr = _cupy.empty(m + 1, 'i')
1219
+ indices = _cupy.empty(nnz, 'i')
1220
+
1221
+ _call_cusparse(
1222
+ 'dense2csr', x.dtype,
1223
+ handle, m, n, descr.descriptor,
1224
+ x.data.ptr, m, nnz_per_row.data.ptr,
1225
+ data.data.ptr, indptr.data.ptr, indices.data.ptr)
1226
+ # Note that a descriptor is recreated
1227
+ csr = cupyx.scipy.sparse.csr_matrix((data, indices, indptr), shape=x.shape)
1228
+ csr._has_canonical_format = True
1229
+ return csr
1230
+
1231
+
1232
+ def csr2csr_compress(x, tol):
1233
+ if not check_availability('csr2csr_compress'):
1234
+ raise RuntimeError('csr2csr_compress is not available.')
1235
+
1236
+ assert x.dtype.char in 'fdFD'
1237
+
1238
+ handle = _device.get_cusparse_handle()
1239
+ m, n = x.shape
1240
+
1241
+ nnz_per_row = _cupy.empty(m, 'i')
1242
+ nnz = _call_cusparse(
1243
+ 'nnz_compress', x.dtype,
1244
+ handle, m, x._descr.descriptor,
1245
+ x.data.data.ptr, x.indptr.data.ptr, nnz_per_row.data.ptr, tol)
1246
+ data = _cupy.zeros(nnz, x.dtype)
1247
+ indptr = _cupy.empty(m + 1, 'i')
1248
+ indices = _cupy.zeros(nnz, 'i')
1249
+ _call_cusparse(
1250
+ 'csr2csr_compress', x.dtype,
1251
+ handle, m, n, x._descr.descriptor,
1252
+ x.data.data.ptr, x.indices.data.ptr, x.indptr.data.ptr,
1253
+ x.nnz, nnz_per_row.data.ptr, data.data.ptr, indices.data.ptr,
1254
+ indptr.data.ptr, tol)
1255
+
1256
+ return cupyx.scipy.sparse.csr_matrix(
1257
+ (data, indices, indptr), shape=x.shape)
1258
+
1259
+
1260
+ def _dtype_to_IndexType(dtype):
1261
+ if dtype == 'uint16':
1262
+ return _cusparse.CUSPARSE_INDEX_16U
1263
+ elif dtype == 'int32':
1264
+ return _cusparse.CUSPARSE_INDEX_32I
1265
+ elif dtype == 'int64':
1266
+ return _cusparse.CUSPARSE_INDEX_64I
1267
+ else:
1268
+ raise TypeError
1269
+
1270
+
1271
+ class BaseDescriptor(object):
1272
+
1273
+ def __init__(self, descriptor, get=None, destroyer=None):
1274
+ self.desc = descriptor
1275
+ self.get = get
1276
+ self.destroy = destroyer
1277
+
1278
+ def __del__(self, is_shutting_down=_util.is_shutting_down):
1279
+ if is_shutting_down():
1280
+ return
1281
+ if self.destroy is None:
1282
+ self.desc = None
1283
+ elif self.desc is not None:
1284
+ self.destroy(self.desc)
1285
+ self.desc = None
1286
+
1287
+ def __getattr__(self, name):
1288
+ if self.get is not None:
1289
+ return getattr(self.get(self.desc), name)
1290
+ raise AttributeError
1291
+
1292
+
1293
+ class SpMatDescriptor(BaseDescriptor):
1294
+
1295
+ @classmethod
1296
+ def create(cls, a):
1297
+ assert cupyx.scipy.sparse.issparse(a)
1298
+ rows, cols = a.shape
1299
+ idx_base = _cusparse.CUSPARSE_INDEX_BASE_ZERO
1300
+ cuda_dtype = _dtype.to_cuda_dtype(a.dtype)
1301
+ if a.format == 'csr':
1302
+ desc = _cusparse.createCsr(
1303
+ rows, cols, a.nnz, a.indptr.data.ptr, a.indices.data.ptr,
1304
+ a.data.data.ptr, _dtype_to_IndexType(a.indptr.dtype),
1305
+ _dtype_to_IndexType(a.indices.dtype), idx_base, cuda_dtype)
1306
+ get = _cusparse.csrGet
1307
+ elif a.format == 'coo':
1308
+ desc = _cusparse.createCoo(
1309
+ rows, cols, a.nnz, a.row.data.ptr, a.col.data.ptr,
1310
+ a.data.data.ptr, _dtype_to_IndexType(a.row.dtype),
1311
+ idx_base, cuda_dtype)
1312
+ get = _cusparse.cooGet
1313
+ elif a.format == 'csc':
1314
+ desc = _cusparse.createCsc(
1315
+ rows, cols, a.nnz, a.indptr.data.ptr, a.indices.data.ptr,
1316
+ a.data.data.ptr, _dtype_to_IndexType(a.indptr.dtype),
1317
+ _dtype_to_IndexType(a.indices.dtype), idx_base, cuda_dtype)
1318
+ get = None
1319
+ else:
1320
+ raise ValueError('csr, csc and coo format are supported '
1321
+ '(actual: {}).'.format(a.format))
1322
+ destroy = _cusparse.destroySpMat
1323
+ return SpMatDescriptor(desc, get, destroy)
1324
+
1325
+ def set_attribute(self, attribute, data):
1326
+ _cusparse.spMatSetAttribute(self.desc, attribute, data)
1327
+
1328
+
1329
+ class SpVecDescriptor(BaseDescriptor):
1330
+
1331
+ @classmethod
1332
+ def create(cls, idx, x):
1333
+ nnz = x.size
1334
+ cuda_dtype = _dtype.to_cuda_dtype(x.dtype)
1335
+ desc = _cusparse.createSpVec(nnz, nnz, idx.data.ptr, x.data.ptr,
1336
+ _dtype_to_IndexType(idx.dtype),
1337
+ _cusparse.CUSPARSE_INDEX_BASE_ZERO,
1338
+ cuda_dtype)
1339
+ get = _cusparse.spVecGet
1340
+ destroy = _cusparse.destroySpVec
1341
+ return SpVecDescriptor(desc, get, destroy)
1342
+
1343
+
1344
+ class DnVecDescriptor(BaseDescriptor):
1345
+
1346
+ @classmethod
1347
+ def create(cls, x):
1348
+ cuda_dtype = _dtype.to_cuda_dtype(x.dtype)
1349
+ desc = _cusparse.createDnVec(x.size, x.data.ptr, cuda_dtype)
1350
+ get = _cusparse.dnVecGet
1351
+ destroy = _cusparse.destroyDnVec
1352
+ return DnVecDescriptor(desc, get, destroy)
1353
+
1354
+
1355
+ class DnMatDescriptor(BaseDescriptor):
1356
+
1357
+ @classmethod
1358
+ def create(cls, a):
1359
+ assert a.ndim == 2
1360
+ assert a.flags.f_contiguous
1361
+ rows, cols = a.shape
1362
+ ld = rows
1363
+ cuda_dtype = _dtype.to_cuda_dtype(a.dtype)
1364
+ desc = _cusparse.createDnMat(rows, cols, ld, a.data.ptr, cuda_dtype,
1365
+ _cusparse.CUSPARSE_ORDER_COL)
1366
+ get = _cusparse.dnMatGet
1367
+ destroy = _cusparse.destroyDnMat
1368
+ return DnMatDescriptor(desc, get, destroy)
1369
+
1370
+
1371
+ def spmv(a, x, y=None, alpha=1, beta=0, transa=False):
1372
+ """Multiplication of sparse matrix and dense vector.
1373
+
1374
+ .. math::
1375
+
1376
+ y = \\alpha * op(A) x + \\beta * y
1377
+
1378
+ Args:
1379
+ a (cupyx.scipy.sparse.csr_matrix, csc_matrix or coo_matrix):
1380
+ Sparse matrix A
1381
+ x (cupy.ndarray): Dense vector x
1382
+ y (cupy.ndarray or None): Dense vector y
1383
+ alpha (scalar): Coefficient
1384
+ beta (scalar): Coefficient
1385
+ transa (bool): If ``True``, op(A) = transpose of A.
1386
+
1387
+ Returns:
1388
+ cupy.ndarray
1389
+ """
1390
+ if not check_availability('spmv'):
1391
+ raise RuntimeError('spmv is not available.')
1392
+
1393
+ if isinstance(a, cupyx.scipy.sparse.csc_matrix):
1394
+ aT = a.T
1395
+ if not isinstance(aT, cupyx.scipy.sparse.csr_matrix):
1396
+ msg = 'aT must be csr_matrix (actual: {})'.format(type(aT))
1397
+ raise TypeError(msg)
1398
+ a = aT
1399
+ transa = not transa
1400
+ if not isinstance(a, (cupyx.scipy.sparse.csr_matrix,
1401
+ cupyx.scipy.sparse.coo_matrix)):
1402
+ raise TypeError('unsupported type (actual: {})'.format(type(a)))
1403
+ a_shape = a.shape if not transa else a.shape[::-1]
1404
+ if a_shape[1] != len(x):
1405
+ raise ValueError('dimension mismatch')
1406
+ assert a.has_canonical_format
1407
+
1408
+ m, n = a_shape
1409
+ a, x, y = _cast_common_type(a, x, y)
1410
+ if y is None:
1411
+ y = _cupy.zeros(m, a.dtype)
1412
+ elif len(y) != m:
1413
+ raise ValueError('dimension mismatch')
1414
+ if a.nnz == 0:
1415
+ y.fill(0)
1416
+ return y
1417
+
1418
+ desc_a = SpMatDescriptor.create(a)
1419
+ desc_x = DnVecDescriptor.create(x)
1420
+ desc_y = DnVecDescriptor.create(y)
1421
+
1422
+ handle = _device.get_cusparse_handle()
1423
+ op_a = _transpose_flag(transa)
1424
+ alpha = _numpy.array(alpha, a.dtype).ctypes
1425
+ beta = _numpy.array(beta, a.dtype).ctypes
1426
+ cuda_dtype = _dtype.to_cuda_dtype(a.dtype)
1427
+ alg = _cusparse.CUSPARSE_MV_ALG_DEFAULT
1428
+ buff_size = _cusparse.spMV_bufferSize(handle, op_a, alpha.data,
1429
+ desc_a.desc, desc_x.desc, beta.data,
1430
+ desc_y.desc, cuda_dtype, alg)
1431
+ buff = _cupy.empty(buff_size, _cupy.int8)
1432
+ _cusparse.spMV(handle, op_a, alpha.data, desc_a.desc, desc_x.desc,
1433
+ beta.data, desc_y.desc, cuda_dtype, alg, buff.data.ptr)
1434
+
1435
+ return y
1436
+
1437
+
1438
+ def spmm(a, b, c=None, alpha=1, beta=0, transa=False, transb=False):
1439
+ """Multiplication of sparse matrix and dense matrix.
1440
+
1441
+ .. math::
1442
+
1443
+ C = \\alpha * op(A) op(B) + \\beta * C
1444
+
1445
+ Args:
1446
+ a (cupyx.scipy.sparse.csr_matrix, csc_matrix or coo_matrix):
1447
+ Sparse matrix A
1448
+ b (cupy.ndarray): Dense matrix B
1449
+ c (cupy.ndarray or None): Dense matrix C
1450
+ alpha (scalar): Coefficient
1451
+ beta (scalar): Coefficient
1452
+ transa (bool): If ``True``, op(A) = transpose of A.
1453
+ transb (bool): If ``True``, op(B) = transpose of B.
1454
+
1455
+ Returns:
1456
+ cupy.ndarray
1457
+ """
1458
+ if not check_availability('spmm'):
1459
+ raise RuntimeError('spmm is not available.')
1460
+
1461
+ assert a.ndim == b.ndim == 2
1462
+ assert b.flags.f_contiguous
1463
+ assert c is None or c.flags.f_contiguous
1464
+
1465
+ if isinstance(a, cupyx.scipy.sparse.csc_matrix):
1466
+ aT = a.T
1467
+ if not isinstance(aT, cupyx.scipy.sparse.csr_matrix):
1468
+ msg = 'aT must be csr_matrix (actual: {})'.format(type(aT))
1469
+ raise TypeError(msg)
1470
+ a = aT
1471
+ transa = not transa
1472
+ if not isinstance(a, (cupyx.scipy.sparse.csr_matrix,
1473
+ cupyx.scipy.sparse.coo_matrix)):
1474
+ raise TypeError('unsupported type (actual: {})'.format(type(a)))
1475
+ a_shape = a.shape if not transa else a.shape[::-1]
1476
+ b_shape = b.shape if not transb else b.shape[::-1]
1477
+ if a_shape[1] != b_shape[0]:
1478
+ raise ValueError('dimension mismatch')
1479
+ assert a.has_canonical_format
1480
+
1481
+ m, k = a_shape
1482
+ _, n = b_shape
1483
+ a, b, c = _cast_common_type(a, b, c)
1484
+ if c is None:
1485
+ c = _cupy.zeros((m, n), a.dtype, 'F')
1486
+ elif c.shape[0] != m or c.shape[1] != n:
1487
+ raise ValueError('dimension mismatch')
1488
+ if a.nnz == 0:
1489
+ c.fill(0)
1490
+ return c
1491
+
1492
+ desc_a = SpMatDescriptor.create(a)
1493
+ desc_b = DnMatDescriptor.create(b)
1494
+ desc_c = DnMatDescriptor.create(c)
1495
+
1496
+ handle = _device.get_cusparse_handle()
1497
+ op_a = _transpose_flag(transa)
1498
+ op_b = _transpose_flag(transb)
1499
+ alpha = _numpy.array(alpha, a.dtype).ctypes
1500
+ beta = _numpy.array(beta, a.dtype).ctypes
1501
+ cuda_dtype = _dtype.to_cuda_dtype(a.dtype)
1502
+ alg = _cusparse.CUSPARSE_MM_ALG_DEFAULT
1503
+ buff_size = _cusparse.spMM_bufferSize(handle, op_a, op_b, alpha.data,
1504
+ desc_a.desc, desc_b.desc, beta.data,
1505
+ desc_c.desc, cuda_dtype, alg)
1506
+ buff = _cupy.empty(buff_size, _cupy.int8)
1507
+ buff_size = _cusparse.spMM(handle, op_a, op_b, alpha.data, desc_a.desc,
1508
+ desc_b.desc, beta.data, desc_c.desc,
1509
+ cuda_dtype, alg, buff.data.ptr)
1510
+
1511
+ return c
1512
+
1513
+
1514
+ def csrsm2(a, b, alpha=1.0, lower=True, unit_diag=False, transa=False,
1515
+ blocking=True, level_info=False):
1516
+ """Solves a sparse triangular linear system op(a) * x = alpha * b.
1517
+
1518
+ Args:
1519
+ a (cupyx.scipy.sparse.csr_matrix or cupyx.scipy.sparse.csc_matrix):
1520
+ Sparse matrix with dimension ``(M, M)``.
1521
+ b (cupy.ndarray): Dense vector or matrix with dimension ``(M)`` or
1522
+ ``(M, K)``.
1523
+ alpha (float or complex): Coefficient.
1524
+ lower (bool):
1525
+ True: ``a`` is lower triangle matrix.
1526
+ False: ``a`` is upper triangle matrix.
1527
+ unit_diag (bool):
1528
+ True: diagonal part of ``a`` has unit elements.
1529
+ False: diagonal part of ``a`` has non-unit elements.
1530
+ transa (bool or str): True, False, 'N', 'T' or 'H'.
1531
+ 'N' or False: op(a) == ``a``.
1532
+ 'T' or True: op(a) == ``a.T``.
1533
+ 'H': op(a) == ``a.conj().T``.
1534
+ blocking (bool):
1535
+ True: blocking algorithm is used.
1536
+ False: non-blocking algorithm is used.
1537
+ level_info (bool):
1538
+ True: solves it with level information.
1539
+ False: solves it without level information.
1540
+
1541
+ Note: ``b`` will be overwritten.
1542
+ """
1543
+ if not check_availability('csrsm2'):
1544
+ raise RuntimeError('csrsm2 is not available.')
1545
+
1546
+ if not (cupyx.scipy.sparse.isspmatrix_csr(a) or
1547
+ cupyx.scipy.sparse.isspmatrix_csc(a)):
1548
+ raise ValueError('a must be CSR or CSC sparse matrix')
1549
+ if not isinstance(b, _cupy.ndarray):
1550
+ raise ValueError('b must be cupy.ndarray')
1551
+ if b.ndim not in (1, 2):
1552
+ raise ValueError('b.ndim must be 1 or 2')
1553
+ if not (a.shape[0] == a.shape[1] == b.shape[0]):
1554
+ raise ValueError('invalid shape')
1555
+ if a.dtype != b.dtype:
1556
+ raise TypeError('dtype mismatch')
1557
+
1558
+ if lower is True:
1559
+ fill_mode = _cusparse.CUSPARSE_FILL_MODE_LOWER
1560
+ elif lower is False:
1561
+ fill_mode = _cusparse.CUSPARSE_FILL_MODE_UPPER
1562
+ else:
1563
+ raise ValueError('Unknown lower (actual: {})'.format(lower))
1564
+
1565
+ if unit_diag is False:
1566
+ diag_type = _cusparse.CUSPARSE_DIAG_TYPE_NON_UNIT
1567
+ elif unit_diag is True:
1568
+ diag_type = _cusparse.CUSPARSE_DIAG_TYPE_UNIT
1569
+ else:
1570
+ raise ValueError('Unknown unit_diag (actual: {})'.format(unit_diag))
1571
+
1572
+ if blocking is False:
1573
+ algo = 0
1574
+ elif blocking is True:
1575
+ algo = 1
1576
+ else:
1577
+ raise ValueError('Unknown blocking (actual: {})'.format(blocking))
1578
+
1579
+ if level_info is False:
1580
+ policy = _cusparse.CUSPARSE_SOLVE_POLICY_NO_LEVEL
1581
+ elif level_info is True:
1582
+ policy = _cusparse.CUSPARSE_SOLVE_POLICY_USE_LEVEL
1583
+ else:
1584
+ raise ValueError('Unknown level_info (actual: {})'.format(level_info))
1585
+
1586
+ dtype = a.dtype
1587
+ if dtype.char == 'f':
1588
+ t = 's'
1589
+ elif dtype.char == 'd':
1590
+ t = 'd'
1591
+ elif dtype.char == 'F':
1592
+ t = 'c'
1593
+ elif dtype.char == 'D':
1594
+ t = 'z'
1595
+ else:
1596
+ raise TypeError('Invalid dtype (actual: {})'.format(dtype))
1597
+ helper = getattr(_cusparse, t + 'csrsm2_bufferSizeExt')
1598
+ analysis = getattr(_cusparse, t + 'csrsm2_analysis')
1599
+ solve = getattr(_cusparse, t + 'csrsm2_solve')
1600
+
1601
+ if transa is False or transa == 'N':
1602
+ transa = _cusparse.CUSPARSE_OPERATION_NON_TRANSPOSE
1603
+ elif transa is True or transa == 'T':
1604
+ transa = _cusparse.CUSPARSE_OPERATION_TRANSPOSE
1605
+ elif transa == 'H':
1606
+ if dtype.char in 'fd':
1607
+ transa = _cusparse.CUSPARSE_OPERATION_TRANSPOSE
1608
+ else:
1609
+ transa = _cusparse.CUSPARSE_OPERATION_CONJUGATE_TRANSPOSE
1610
+ else:
1611
+ raise ValueError('Unknown transa (actual: {})'.format(transa))
1612
+
1613
+ if cupyx.scipy.sparse.isspmatrix_csc(a):
1614
+ if transa == _cusparse.CUSPARSE_OPERATION_CONJUGATE_TRANSPOSE:
1615
+ raise ValueError('If matrix is CSC format and complex dtype,'
1616
+ 'transa must not be \'H\'')
1617
+ a = a.T
1618
+ assert cupyx.scipy.sparse.isspmatrix_csr(a)
1619
+ transa = 1 - transa
1620
+ fill_mode = 1 - fill_mode
1621
+
1622
+ m = a.shape[0]
1623
+ nrhs = 1 if b.ndim == 1 else b.shape[1]
1624
+ if b._f_contiguous:
1625
+ transb = _cusparse.CUSPARSE_OPERATION_NON_TRANSPOSE
1626
+ ldb = m
1627
+ elif b._c_contiguous:
1628
+ transb = _cusparse.CUSPARSE_OPERATION_TRANSPOSE
1629
+ ldb = nrhs
1630
+ else:
1631
+ raise ValueError('b must be F-contiguous or C-contiguous.')
1632
+
1633
+ handle = _device.get_cusparse_handle()
1634
+ alpha = _numpy.array(alpha, dtype=dtype)
1635
+ a_desc = MatDescriptor.create()
1636
+ a_desc.set_mat_type(_cusparse.CUSPARSE_MATRIX_TYPE_GENERAL)
1637
+ a_desc.set_mat_index_base(_cusparse.CUSPARSE_INDEX_BASE_ZERO)
1638
+ a_desc.set_mat_fill_mode(fill_mode)
1639
+ a_desc.set_mat_diag_type(diag_type)
1640
+ info = _cusparse.createCsrsm2Info()
1641
+ ws_size = helper(handle, algo, transa, transb, m, nrhs, a.nnz,
1642
+ alpha.ctypes.data, a_desc.descriptor, a.data.data.ptr,
1643
+ a.indptr.data.ptr, a.indices.data.ptr, b.data.ptr, ldb,
1644
+ info, policy)
1645
+ ws = _cupy.empty((ws_size,), dtype=_numpy.int8)
1646
+
1647
+ analysis(handle, algo, transa, transb, m, nrhs, a.nnz, alpha.ctypes.data,
1648
+ a_desc.descriptor, a.data.data.ptr, a.indptr.data.ptr,
1649
+ a.indices.data.ptr, b.data.ptr, ldb, info, policy, ws.data.ptr)
1650
+
1651
+ solve(handle, algo, transa, transb, m, nrhs, a.nnz, alpha.ctypes.data,
1652
+ a_desc.descriptor, a.data.data.ptr, a.indptr.data.ptr,
1653
+ a.indices.data.ptr, b.data.ptr, ldb, info, policy, ws.data.ptr)
1654
+
1655
+ # without sync we'd get either segfault or cuda context error
1656
+ _stream.get_current_stream().synchronize()
1657
+ _cusparse.destroyCsrsm2Info(info)
1658
+
1659
+
1660
+ def csrilu02(a, level_info=False):
1661
+ """Computes incomplete LU decomposition for a sparse square matrix.
1662
+
1663
+ Args:
1664
+ a (cupyx.scipy.sparse.csr_matrix):
1665
+ Sparse matrix with dimension ``(M, M)``.
1666
+ level_info (bool):
1667
+ True: solves it with level information.
1668
+ False: solves it without level information.
1669
+
1670
+ Note: ``a`` will be overwritten. This function does not support fill-in
1671
+ (only ILU(0) is supported) nor pivoting.
1672
+ """
1673
+ if not check_availability('csrilu02'):
1674
+ raise RuntimeError('csrilu02 is not available.')
1675
+
1676
+ if not cupyx.scipy.sparse.isspmatrix_csr(a):
1677
+ raise TypeError('a must be CSR sparse matrix')
1678
+ if a.shape[0] != a.shape[1]:
1679
+ raise ValueError('invalid shape (a.shape: {})'.format(a.shape))
1680
+
1681
+ if level_info is False:
1682
+ policy = _cusparse.CUSPARSE_SOLVE_POLICY_NO_LEVEL
1683
+ elif level_info is True:
1684
+ policy = _cusparse.CUSPARSE_SOLVE_POLICY_USE_LEVEL
1685
+ else:
1686
+ raise ValueError('Unknown level_info (actual: {})'.format(level_info))
1687
+
1688
+ dtype = a.dtype
1689
+ if dtype.char == 'f':
1690
+ t = 's'
1691
+ elif dtype.char == 'd':
1692
+ t = 'd'
1693
+ elif dtype.char == 'F':
1694
+ t = 'c'
1695
+ elif dtype.char == 'D':
1696
+ t = 'z'
1697
+ else:
1698
+ raise TypeError('Invalid dtype (actual: {})'.format(dtype))
1699
+ helper = getattr(_cusparse, t + 'csrilu02_bufferSize')
1700
+ analysis = getattr(_cusparse, t + 'csrilu02_analysis')
1701
+ solve = getattr(_cusparse, t + 'csrilu02')
1702
+ check = getattr(_cusparse, 'xcsrilu02_zeroPivot')
1703
+
1704
+ handle = _device.get_cusparse_handle()
1705
+ m = a.shape[0]
1706
+ nnz = a.nnz
1707
+ desc = MatDescriptor.create()
1708
+ desc.set_mat_type(_cusparse.CUSPARSE_MATRIX_TYPE_GENERAL)
1709
+ desc.set_mat_index_base(_cusparse.CUSPARSE_INDEX_BASE_ZERO)
1710
+ info = _cusparse.createCsrilu02Info()
1711
+ ws_size = helper(handle, m, nnz, desc.descriptor, a.data.data.ptr,
1712
+ a.indptr.data.ptr, a.indices.data.ptr, info)
1713
+ ws = _cupy.empty((ws_size,), dtype=_numpy.int8)
1714
+ position = _numpy.empty((1,), dtype=_numpy.int32)
1715
+
1716
+ analysis(handle, m, nnz, desc.descriptor, a.data.data.ptr,
1717
+ a.indptr.data.ptr, a.indices.data.ptr, info, policy, ws.data.ptr)
1718
+ try:
1719
+ check(handle, info, position.ctypes.data)
1720
+ except Exception:
1721
+ raise ValueError('a({0},{0}) is missing'.format(position[0]))
1722
+
1723
+ solve(handle, m, nnz, desc.descriptor, a.data.data.ptr,
1724
+ a.indptr.data.ptr, a.indices.data.ptr, info, policy, ws.data.ptr)
1725
+ try:
1726
+ check(handle, info, position.ctypes.data)
1727
+ except Exception:
1728
+ raise ValueError('u({0},{0}) is zero'.format(position[0]))
1729
+
1730
+
1731
+ def denseToSparse(x, format='csr'):
1732
+ """Converts a dense matrix into a CSR, CSC or COO format.
1733
+
1734
+ Args:
1735
+ x (cupy.ndarray): A matrix to be converted.
1736
+ format (str): Format of converted matrix. It must be either 'csr',
1737
+ 'csc' or 'coo'.
1738
+
1739
+ Returns:
1740
+ cupyx.scipy.sparse.spmatrix: A converted sparse matrix.
1741
+
1742
+ """
1743
+ if not check_availability('denseToSparse'):
1744
+ raise RuntimeError('denseToSparse is not available.')
1745
+
1746
+ assert x.ndim == 2
1747
+ assert x.dtype.char in 'fdFD'
1748
+ x = _cupy.asfortranarray(x)
1749
+ desc_x = DnMatDescriptor.create(x)
1750
+ if format == 'csr':
1751
+ y = cupyx.scipy.sparse.csr_matrix(x.shape, dtype=x.dtype)
1752
+ elif format == 'csc':
1753
+ y = cupyx.scipy.sparse.csc_matrix(x.shape, dtype=x.dtype)
1754
+ elif format == 'coo':
1755
+ y = cupyx.scipy.sparse.coo_matrix(x.shape, dtype=x.dtype)
1756
+ else:
1757
+ raise TypeError('unsupported format (actual: {})'.format(format))
1758
+ desc_y = SpMatDescriptor.create(y)
1759
+ algo = _cusparse.CUSPARSE_DENSETOSPARSE_ALG_DEFAULT
1760
+ handle = _device.get_cusparse_handle()
1761
+ buff_size = _cusparse.denseToSparse_bufferSize(handle, desc_x.desc,
1762
+ desc_y.desc, algo)
1763
+ buff = _cupy.empty(buff_size, _cupy.int8)
1764
+ _cusparse.denseToSparse_analysis(handle, desc_x.desc,
1765
+ desc_y.desc, algo, buff.data.ptr)
1766
+ num_rows_tmp = _numpy.array(0, dtype='int64')
1767
+ num_cols_tmp = _numpy.array(0, dtype='int64')
1768
+ nnz = _numpy.array(0, dtype='int64')
1769
+ _cusparse.spMatGetSize(desc_y.desc, num_rows_tmp.ctypes.data,
1770
+ num_cols_tmp.ctypes.data, nnz.ctypes.data)
1771
+ nnz = int(nnz)
1772
+ if _runtime.is_hip:
1773
+ if nnz == 0:
1774
+ raise ValueError('hipSPARSE currently cannot handle '
1775
+ 'sparse matrices with null ptrs')
1776
+ if format == 'csr':
1777
+ indptr = y.indptr
1778
+ indices = _cupy.empty(nnz, 'i')
1779
+ data = _cupy.empty(nnz, x.dtype)
1780
+ y = cupyx.scipy.sparse.csr_matrix((data, indices, indptr),
1781
+ shape=x.shape)
1782
+ elif format == 'csc':
1783
+ indptr = y.indptr
1784
+ indices = _cupy.empty(nnz, 'i')
1785
+ data = _cupy.empty(nnz, x.dtype)
1786
+ y = cupyx.scipy.sparse.csc_matrix((data, indices, indptr),
1787
+ shape=x.shape)
1788
+ elif format == 'coo':
1789
+ row = _cupy.zeros(nnz, 'i')
1790
+ col = _cupy.zeros(nnz, 'i')
1791
+ # Note: I would like to use empty() here, but that might cause an
1792
+ # exception in the row/col number check when creating the coo_matrix,
1793
+ # so I used zeros() instead.
1794
+ data = _cupy.empty(nnz, x.dtype)
1795
+ y = cupyx.scipy.sparse.coo_matrix((data, (row, col)), shape=x.shape)
1796
+ desc_y = SpMatDescriptor.create(y)
1797
+ _cusparse.denseToSparse_convert(handle, desc_x.desc,
1798
+ desc_y.desc, algo, buff.data.ptr)
1799
+ y._has_canonical_format = True
1800
+ return y
1801
+
1802
+
1803
+ def sparseToDense(x, out=None):
1804
+ """Converts sparse matrix to a dense matrix.
1805
+
1806
+ Args:
1807
+ x (cupyx.scipy.sparse.spmatrix): A sparse matrix to convert.
1808
+ out (cupy.ndarray or None): A dense metrix to store the result.
1809
+ It must be F-contiguous.
1810
+
1811
+ Returns:
1812
+ cupy.ndarray: A converted dense matrix.
1813
+
1814
+ """
1815
+ if not check_availability('sparseToDense'):
1816
+ raise RuntimeError('sparseToDense is not available.')
1817
+
1818
+ dtype = x.dtype
1819
+ assert dtype.char in 'fdFD'
1820
+ if out is None:
1821
+ out = _cupy.zeros(x.shape, dtype=dtype, order='F')
1822
+ else:
1823
+ assert out.flags.f_contiguous
1824
+ assert out.dtype == dtype
1825
+
1826
+ desc_x = SpMatDescriptor.create(x)
1827
+ desc_out = DnMatDescriptor.create(out)
1828
+ algo = _cusparse.CUSPARSE_SPARSETODENSE_ALG_DEFAULT
1829
+ handle = _device.get_cusparse_handle()
1830
+ buff_size = _cusparse.sparseToDense_bufferSize(handle, desc_x.desc,
1831
+ desc_out.desc, algo)
1832
+ buff = _cupy.empty(buff_size, _cupy.int8)
1833
+ if _runtime.is_hip:
1834
+ if x.nnz == 0:
1835
+ raise ValueError('hipSPARSE currently cannot handle '
1836
+ 'sparse matrices with null ptrs')
1837
+ _cusparse.sparseToDense(handle, desc_x.desc,
1838
+ desc_out.desc, algo, buff.data.ptr)
1839
+
1840
+ return out
1841
+
1842
+
1843
+ def spsm(a, b, alpha=1.0, lower=True, unit_diag=False, transa=False):
1844
+ """Solves a sparse triangular linear system op(a) * x = alpha * op(b).
1845
+
1846
+ Args:
1847
+ a (cupyx.scipy.sparse.csr_matrix or cupyx.scipy.sparse.coo_matrix):
1848
+ Sparse matrix with dimension ``(M, M)``.
1849
+ b (cupy.ndarray): Dense matrix with dimension ``(M, K)``.
1850
+ alpha (float or complex): Coefficient.
1851
+ lower (bool):
1852
+ True: ``a`` is lower triangle matrix.
1853
+ False: ``a`` is upper triangle matrix.
1854
+ unit_diag (bool):
1855
+ True: diagonal part of ``a`` has unit elements.
1856
+ False: diagonal part of ``a`` has non-unit elements.
1857
+ transa (bool or str): True, False, 'N', 'T' or 'H'.
1858
+ 'N' or False: op(a) == ``a``.
1859
+ 'T' or True: op(a) == ``a.T``.
1860
+ 'H': op(a) == ``a.conj().T``.
1861
+ """
1862
+ if not check_availability('spsm'):
1863
+ raise RuntimeError('spsm is not available.')
1864
+
1865
+ # Canonicalise transa
1866
+ if transa is False:
1867
+ transa = 'N'
1868
+ elif transa is True:
1869
+ transa = 'T'
1870
+ elif transa not in 'NTH':
1871
+ raise ValueError(f'Unknown transa (actual: {transa})')
1872
+
1873
+ # Check A's type and sparse format
1874
+ if cupyx.scipy.sparse.isspmatrix_csr(a):
1875
+ pass
1876
+ elif cupyx.scipy.sparse.isspmatrix_csc(a):
1877
+ if transa == 'N':
1878
+ a = a.T
1879
+ transa = 'T'
1880
+ elif transa == 'T':
1881
+ a = a.T
1882
+ transa = 'N'
1883
+ elif transa == 'H':
1884
+ a = a.conj().T
1885
+ transa = 'N'
1886
+ lower = not lower
1887
+ elif cupyx.scipy.sparse.isspmatrix_coo(a):
1888
+ pass
1889
+ else:
1890
+ raise ValueError('a must be CSR, CSC or COO sparse matrix')
1891
+ assert a.has_canonical_format
1892
+
1893
+ # Check B's ndim
1894
+ if b.ndim == 1:
1895
+ is_b_vector = True
1896
+ b = b.reshape(-1, 1)
1897
+ elif b.ndim == 2:
1898
+ is_b_vector = False
1899
+ else:
1900
+ raise ValueError('b.ndim must be 1 or 2')
1901
+
1902
+ # Check shapes
1903
+ if not (a.shape[0] == a.shape[1] == b.shape[0]):
1904
+ raise ValueError('mismatched shape')
1905
+
1906
+ # Check dtypes
1907
+ dtype = a.dtype
1908
+ if dtype.char not in 'fdFD':
1909
+ raise TypeError('Invalid dtype (actual: {})'.format(dtype))
1910
+ if dtype != b.dtype:
1911
+ raise TypeError('dtype mismatch')
1912
+
1913
+ # Prepare fill mode
1914
+ if lower is True:
1915
+ fill_mode = _cusparse.CUSPARSE_FILL_MODE_LOWER
1916
+ elif lower is False:
1917
+ fill_mode = _cusparse.CUSPARSE_FILL_MODE_UPPER
1918
+ else:
1919
+ raise ValueError('Unknown lower (actual: {})'.format(lower))
1920
+
1921
+ # Prepare diag type
1922
+ if unit_diag is False:
1923
+ diag_type = _cusparse.CUSPARSE_DIAG_TYPE_NON_UNIT
1924
+ elif unit_diag is True:
1925
+ diag_type = _cusparse.CUSPARSE_DIAG_TYPE_UNIT
1926
+ else:
1927
+ raise ValueError('Unknown unit_diag (actual: {})'.format(unit_diag))
1928
+
1929
+ # Prepare op_a
1930
+ if transa == 'N':
1931
+ op_a = _cusparse.CUSPARSE_OPERATION_NON_TRANSPOSE
1932
+ elif transa == 'T':
1933
+ op_a = _cusparse.CUSPARSE_OPERATION_TRANSPOSE
1934
+ else: # transa == 'H'
1935
+ if dtype.char in 'fd':
1936
+ op_a = _cusparse.CUSPARSE_OPERATION_TRANSPOSE
1937
+ else:
1938
+ op_a = _cusparse.CUSPARSE_OPERATION_CONJUGATE_TRANSPOSE
1939
+
1940
+ # Prepare op_b
1941
+ if b._f_contiguous:
1942
+ op_b = _cusparse.CUSPARSE_OPERATION_NON_TRANSPOSE
1943
+ elif b._c_contiguous:
1944
+ if _cusparse.get_build_version() < 11701: # earlier than CUDA 11.6
1945
+ raise ValueError('b must be F-contiguous.')
1946
+ b = b.T
1947
+ op_b = _cusparse.CUSPARSE_OPERATION_TRANSPOSE
1948
+ else:
1949
+ raise ValueError('b must be F-contiguous or C-contiguous.')
1950
+
1951
+ # Allocate space for matrix C. Note that it is known cusparseSpSM requires
1952
+ # the output matrix zero initialized.
1953
+ m, _ = a.shape
1954
+ if op_b == _cusparse.CUSPARSE_OPERATION_NON_TRANSPOSE:
1955
+ _, n = b.shape
1956
+ else:
1957
+ n, _ = b.shape
1958
+ c_shape = m, n
1959
+ c = _cupy.zeros(c_shape, dtype=a.dtype, order='f')
1960
+
1961
+ # Prepare descriptors and other parameters
1962
+ handle = _device.get_cusparse_handle()
1963
+ mat_a = SpMatDescriptor.create(a)
1964
+ mat_b = DnMatDescriptor.create(b)
1965
+ mat_c = DnMatDescriptor.create(c)
1966
+ spsm_descr = _cusparse.spSM_createDescr()
1967
+ alpha = _numpy.array(alpha, dtype=c.dtype).ctypes
1968
+ cuda_dtype = _dtype.to_cuda_dtype(c.dtype)
1969
+ algo = _cusparse.CUSPARSE_SPSM_ALG_DEFAULT
1970
+
1971
+ try:
1972
+ # Specify Lower|Upper fill mode
1973
+ mat_a.set_attribute(_cusparse.CUSPARSE_SPMAT_FILL_MODE, fill_mode)
1974
+
1975
+ # Specify Unit|Non-Unit diagonal type
1976
+ mat_a.set_attribute(_cusparse.CUSPARSE_SPMAT_DIAG_TYPE, diag_type)
1977
+
1978
+ # Allocate the workspace needed by the succeeding phases
1979
+ buff_size = _cusparse.spSM_bufferSize(
1980
+ handle, op_a, op_b, alpha.data, mat_a.desc, mat_b.desc,
1981
+ mat_c.desc, cuda_dtype, algo, spsm_descr)
1982
+ buff = _cupy.empty(buff_size, dtype=_cupy.int8)
1983
+
1984
+ # Perform the analysis phase
1985
+ _cusparse.spSM_analysis(
1986
+ handle, op_a, op_b, alpha.data, mat_a.desc, mat_b.desc,
1987
+ mat_c.desc, cuda_dtype, algo, spsm_descr, buff.data.ptr)
1988
+
1989
+ # Executes the solve phase
1990
+ _cusparse.spSM_solve(
1991
+ handle, op_a, op_b, alpha.data, mat_a.desc, mat_b.desc,
1992
+ mat_c.desc, cuda_dtype, algo, spsm_descr, buff.data.ptr)
1993
+
1994
+ # Reshape back if B was a vector
1995
+ if is_b_vector:
1996
+ c = c.reshape(-1)
1997
+
1998
+ return c
1999
+
2000
+ finally:
2001
+ # Destroy matrix/vector descriptors
2002
+ _cusparse.spSM_destroyDescr(spsm_descr)
2003
+
2004
+
2005
+ def spgemm(a, b, alpha=1):
2006
+ """Matrix-matrix product for CSR-matrix.
2007
+
2008
+ math::
2009
+ C = alpha * A * B
2010
+
2011
+ Args:
2012
+ a (cupyx.scipy.sparse.csr_matrix): Sparse matrix A.
2013
+ b (cupyx.scipy.sparse.csr_matrix): Sparse matrix B.
2014
+ alpha (scalar): Coefficient
2015
+
2016
+ Returns:
2017
+ cupyx.scipy.sparse.csr_matrix
2018
+
2019
+ """
2020
+ if not check_availability('spgemm'):
2021
+ raise RuntimeError('spgemm is not available.')
2022
+
2023
+ assert a.ndim == b.ndim == 2
2024
+ if not isinstance(a, cupyx.scipy.sparse.csr_matrix):
2025
+ raise TypeError('unsupported type (actual: {})'.format(type(a)))
2026
+ if not isinstance(b, cupyx.scipy.sparse.csr_matrix):
2027
+ raise TypeError('unsupported type (actual: {})'.format(type(b)))
2028
+ assert a.has_canonical_format
2029
+ assert b.has_canonical_format
2030
+ if a.shape[1] != b.shape[0]:
2031
+ raise ValueError('mismatched shape')
2032
+
2033
+ m, k = a.shape
2034
+ _, n = b.shape
2035
+ a, b = _cast_common_type(a, b)
2036
+ c_shape = (m, n)
2037
+ c = cupyx.scipy.sparse.csr_matrix((c_shape), dtype=a.dtype)
2038
+
2039
+ handle = _device.get_cusparse_handle()
2040
+ mat_a = SpMatDescriptor.create(a)
2041
+ mat_b = SpMatDescriptor.create(b)
2042
+ mat_c = SpMatDescriptor.create(c)
2043
+ spgemm_descr = _cusparse.spGEMM_createDescr()
2044
+ op_a = _cusparse.CUSPARSE_OPERATION_NON_TRANSPOSE
2045
+ op_b = _cusparse.CUSPARSE_OPERATION_NON_TRANSPOSE
2046
+ alpha = _numpy.array(alpha, dtype=c.dtype).ctypes
2047
+ beta = _numpy.array(0, dtype=c.dtype).ctypes
2048
+ cuda_dtype = _dtype.to_cuda_dtype(c.dtype)
2049
+ algo = _cusparse.CUSPARSE_SPGEMM_DEFAULT
2050
+ null_ptr = 0
2051
+
2052
+ # Analyze the matrices A and B to understand the memory requirement
2053
+ buff1_size = _cusparse.spGEMM_workEstimation(
2054
+ handle, op_a, op_b, alpha.data, mat_a.desc, mat_b.desc, beta.data,
2055
+ mat_c.desc, cuda_dtype, algo, spgemm_descr, 0, null_ptr)
2056
+ buff1 = _cupy.empty(buff1_size, _cupy.int8)
2057
+ _cusparse.spGEMM_workEstimation(
2058
+ handle, op_a, op_b, alpha.data, mat_a.desc, mat_b.desc, beta.data,
2059
+ mat_c.desc, cuda_dtype, algo, spgemm_descr, buff1_size, buff1.data.ptr)
2060
+
2061
+ # Compute the intermediate product of A and B
2062
+ buff2_size = _cusparse.spGEMM_compute(
2063
+ handle, op_a, op_b, alpha.data, mat_a.desc, mat_b.desc, beta.data,
2064
+ mat_c.desc, cuda_dtype, algo, spgemm_descr, 0, null_ptr)
2065
+ buff2 = _cupy.empty(buff2_size, _cupy.int8)
2066
+ _cusparse.spGEMM_compute(
2067
+ handle, op_a, op_b, alpha.data, mat_a.desc, mat_b.desc, beta.data,
2068
+ mat_c.desc, cuda_dtype, algo, spgemm_descr, buff2_size, buff2.data.ptr)
2069
+
2070
+ # Prepare the arrays for matrix C
2071
+ c_num_rows = _numpy.array(0, dtype='int64')
2072
+ c_num_cols = _numpy.array(0, dtype='int64')
2073
+ c_nnz = _numpy.array(0, dtype='int64')
2074
+ _cusparse.spMatGetSize(mat_c.desc, c_num_rows.ctypes.data,
2075
+ c_num_cols.ctypes.data, c_nnz.ctypes.data)
2076
+ assert c_shape[0] == int(c_num_rows)
2077
+ assert c_shape[1] == int(c_num_cols)
2078
+ c_nnz = int(c_nnz)
2079
+ c_indptr = c.indptr
2080
+ c_indices = _cupy.empty(c_nnz, 'i')
2081
+ c_data = _cupy.empty(c_nnz, c.dtype)
2082
+ _cusparse.csrSetPointers(mat_c.desc, c_indptr.data.ptr, c_indices.data.ptr,
2083
+ c_data.data.ptr)
2084
+
2085
+ # Copy the final product to the matrix C
2086
+ _cusparse.spGEMM_copy(
2087
+ handle, op_a, op_b, alpha.data, mat_a.desc, mat_b.desc, beta.data,
2088
+ mat_c.desc, cuda_dtype, algo, spgemm_descr)
2089
+ c = cupyx.scipy.sparse.csr_matrix((c_data, c_indices, c_indptr),
2090
+ shape=c_shape)
2091
+
2092
+ _cusparse.spGEMM_destroyDescr(spgemm_descr)
2093
+ return c
vllm/lib/python3.10/site-packages/cupyx/fallback_mode/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from cupy import _util
2
+
3
+ # Attributes and Methods for fallback_mode
4
+ # Auto-execute numpy method when corresponding cupy method is not found
5
+
6
+ # "NOQA" to suppress flake8 warning
7
+ from cupyx.fallback_mode.fallback import numpy # NOQA
8
+
9
+
10
+ _util.experimental('cupyx.fallback_mode.numpy')
vllm/lib/python3.10/site-packages/cupyx/fallback_mode/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (314 Bytes). View file
 
vllm/lib/python3.10/site-packages/cupyx/fallback_mode/__pycache__/fallback.cpython-310.pyc ADDED
Binary file (16.4 kB). View file
 
vllm/lib/python3.10/site-packages/cupyx/fallback_mode/__pycache__/notification.cpython-310.pyc ADDED
Binary file (1.86 kB). View file
 
vllm/lib/python3.10/site-packages/cupyx/fallback_mode/fallback.py ADDED
@@ -0,0 +1,596 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ `fallback_mode` for cupy. Whenever a method is not yet implemented in CuPy,
3
+ it will fallback to corresponding NumPy method.
4
+ """
5
+ import types
6
+
7
+ import numpy as np
8
+
9
+ import cupy as cp
10
+
11
+
12
+ from cupyx.fallback_mode import notification
13
+
14
+
15
+ class _RecursiveAttr(object):
16
+ """
17
+ RecursiveAttr class to catch all attributes corresponding to numpy,
18
+ when user calls fallback_mode. numpy is an instance of this class.
19
+ """
20
+
21
+ def __init__(self, numpy_object, cupy_object, array=None):
22
+ """
23
+ _RecursiveAttr initializer.
24
+
25
+ Args:
26
+ numpy_object (method): NumPy method.
27
+ cupy_method (method): Corresponding CuPy method.
28
+ array (ndarray): Acts as flag to know if _RecursiveAttr object
29
+ is called from ``ndarray`` class. Also, acts as container for
30
+ modifying args in case it is called from ``ndarray``.
31
+ None otherwise.
32
+ """
33
+
34
+ self._numpy_object = numpy_object
35
+ self._cupy_object = cupy_object
36
+ self._fallback_array = array
37
+
38
+ def __instancecheck__(self, instance):
39
+ """
40
+ Enable support for isinstance(instance, _RecursiveAttr instance)
41
+ by redirecting it to appropriate isinstance method.
42
+ """
43
+
44
+ if self._cupy_object is not None:
45
+ return isinstance(instance, self._cupy_object)
46
+
47
+ return isinstance(instance, self._numpy_object)
48
+
49
+ def __getattr__(self, attr):
50
+ """
51
+ Catches attributes corresponding to numpy.
52
+
53
+ Runs recursively till attribute gets called.
54
+ Or numpy ScalarType is retrieved.
55
+
56
+ Args:
57
+ attr (str): Attribute of _RecursiveAttr class object.
58
+
59
+ Returns:
60
+ (_RecursiveAttr object, NumPy scalar):
61
+ Returns_RecursiveAttr object with new numpy_object,
62
+ cupy_object. OR
63
+ Returns objects in cupy which is an alias
64
+ of numpy object. OR
65
+ Returns wrapper objects, `ndarray`, `vectorize`.
66
+ """
67
+
68
+ numpy_object = getattr(self._numpy_object, attr)
69
+ cupy_object = getattr(self._cupy_object, attr, None)
70
+
71
+ if numpy_object is np.ndarray:
72
+ return ndarray
73
+
74
+ if numpy_object is np.vectorize:
75
+ return vectorize
76
+
77
+ if numpy_object is cupy_object:
78
+ return numpy_object
79
+
80
+ return _RecursiveAttr(numpy_object, cupy_object)
81
+
82
+ def __repr__(self):
83
+
84
+ if isinstance(self._numpy_object, types.ModuleType):
85
+ return "<numpy = module {}, cupy = module {}>".format(
86
+ self._numpy_object.__name__,
87
+ getattr(self._cupy_object, '__name__', None))
88
+
89
+ return "<numpy = {}, cupy = {}>".format(
90
+ self._numpy_object, self._cupy_object)
91
+
92
+ @property
93
+ def __doc__(self):
94
+ return self._numpy_object.__doc__
95
+
96
+ @staticmethod
97
+ def _is_cupy_compatible(arg):
98
+ """
99
+ Returns False if CuPy's functions never accept the arguments as
100
+ parameters due to the following reasons.
101
+ - The inputs include an object of a NumPy's specific class other than
102
+ `np.ndarray`.
103
+ - The inputs include a dtype which is not supported in CuPy.
104
+ """
105
+
106
+ if isinstance(arg, ndarray):
107
+ if not arg._supports_cupy:
108
+ return False
109
+
110
+ if isinstance(arg, (tuple, list)):
111
+ return all(_RecursiveAttr._is_cupy_compatible(i) for i in arg)
112
+
113
+ if isinstance(arg, dict):
114
+ bools = [_RecursiveAttr._is_cupy_compatible(arg[i]) for i in arg]
115
+ return all(bools)
116
+
117
+ return True
118
+
119
+ def __call__(self, *args, **kwargs):
120
+ """
121
+ Gets invoked when last attribute of _RecursiveAttr class gets called.
122
+ Calls _cupy_object if not None else call _numpy_object.
123
+
124
+ Args:
125
+ args (tuple): Arguments.
126
+ kwargs (dict): Keyword arguments.
127
+
128
+ Returns:
129
+ (res, ndarray): Returns of methods call_cupy or call_numpy
130
+ """
131
+
132
+ if not callable(self._numpy_object):
133
+ raise TypeError("'{}' object is not callable".format(
134
+ type(self._numpy_object).__name__))
135
+
136
+ # _RecursiveAttr gets called from ndarray
137
+ if self._fallback_array is not None:
138
+ args = ((self._fallback_array,) + args)
139
+
140
+ if self._cupy_object is not None and \
141
+ _RecursiveAttr._is_cupy_compatible((args, kwargs)):
142
+ try:
143
+ return _call_cupy(self._cupy_object, args, kwargs)
144
+ except Exception:
145
+ return _call_numpy(self._numpy_object, args, kwargs)
146
+
147
+ notification._dispatch_notification(self._numpy_object)
148
+ return _call_numpy(self._numpy_object, args, kwargs)
149
+
150
+
151
+ numpy = _RecursiveAttr(np, cp)
152
+
153
+
154
+ # -----------------------------------------------------------------------------
155
+ # proxying of ndarray magic methods and wrappers
156
+ # -----------------------------------------------------------------------------
157
+
158
+
159
+ class ndarray(object):
160
+ """
161
+ Wrapper around cupy.ndarray
162
+ Supports cupy.ndarray.__init__ as well as,
163
+ gets initialized with a cupy ndarray.
164
+ """
165
+
166
+ __doc__ = np.ndarray.__doc__
167
+
168
+ def __new__(cls, *args, **kwargs):
169
+ """
170
+ If `_initial_array` and `_supports_cupy` are arguments,
171
+ initialize cls(ndarray).
172
+ Else get cupy.ndarray from provided arguments,
173
+ then initialize cls(ndarray).
174
+ """
175
+ _initial_array = kwargs.get('_initial_array', None)
176
+ if _initial_array is not None:
177
+ return object.__new__(cls)
178
+
179
+ cupy_ndarray_init = cp.ndarray(*args, **kwargs)
180
+ return cls(_initial_array=cupy_ndarray_init, _supports_cupy=True)
181
+
182
+ def __init__(self, *args, **kwargs):
183
+ """
184
+ Args:
185
+ _initial_array (None, cp.ndarray/np.ndarray(including variants)):
186
+ If _initial_array is None, object is not initialized.
187
+ Otherwise, _initial_array (ndarray) would be set to
188
+ _cupy_array and/or _numpy_array depending upon _supports_cupy.
189
+ _supports_cupy (bool): If _supports_cupy is True, _initial_array
190
+ is set as _cupy_array and _numpy_array.
191
+ Otherwise, _initial_array is set as only _numpy_array.
192
+
193
+ Attributes:
194
+ _cupy_array (None or cp.ndarray): ndarray fully compatible with
195
+ CuPy. This will be always set to a ndarray in GPU.
196
+ _numpy_array (None or np.ndarray(including variants)): ndarray not
197
+ supported by CuPy. Such as np.ndarray (where dtype is not in
198
+ '?bhilqBHILQefdFD') and it's variants. This will be always set
199
+ to a ndarray in CPU.
200
+ _supports_cupy (bool): If _supports_cupy is True, data of array
201
+ will contain in _cupy_array and _numpy_array.
202
+ Else only _numpy_array will have the data.
203
+ """
204
+
205
+ _supports_cupy = kwargs.pop('_supports_cupy', None)
206
+ _initial_array = kwargs.pop('_initial_array', None)
207
+ if _initial_array is None:
208
+ return
209
+
210
+ self._cupy_array = None
211
+ self._numpy_array = None
212
+ self.base = None
213
+ self._supports_cupy = _supports_cupy
214
+
215
+ assert isinstance(_initial_array, (cp.ndarray, np.ndarray))
216
+ if _supports_cupy:
217
+ if type(_initial_array) is cp.ndarray:
218
+ # _initial_array is in GPU memory
219
+ # called by _store_array_from_cupy
220
+ self._cupy_array = _initial_array
221
+ self._remember_numpy = False
222
+ else:
223
+ # _initial_array is in CPU memory
224
+ # called by _store_array_from_numpy
225
+ self._numpy_array = _initial_array
226
+ self._remember_numpy = True
227
+ else:
228
+ self._numpy_array = _initial_array
229
+
230
+ @classmethod
231
+ def _store_array_from_cupy(cls, array):
232
+ return cls(_initial_array=array, _supports_cupy=True)
233
+
234
+ @classmethod
235
+ def _store_array_from_numpy(cls, array):
236
+ if type(array) is np.ndarray and \
237
+ array.dtype.kind in '?bhilqBHILQefdFD':
238
+ return cls(_initial_array=array, _supports_cupy=True)
239
+
240
+ return cls(_initial_array=array, _supports_cupy=False)
241
+
242
+ @property
243
+ def dtype(self):
244
+ if self._supports_cupy and not self._remember_numpy:
245
+ return self._cupy_array.dtype
246
+ return self._numpy_array.dtype
247
+
248
+ def __getattr__(self, attr):
249
+ """
250
+ Catches attributes corresponding to ndarray.
251
+
252
+ Args:
253
+ attr (str): Attribute of ndarray class.
254
+
255
+ Returns:
256
+ (_RecursiveAttr object, self._array.attr):
257
+ Returns_RecursiveAttr object with numpy_object, cupy_object.
258
+ Returns self._array.attr if attr is not callable.
259
+ """
260
+
261
+ if self._supports_cupy:
262
+ cupy_object = getattr(cp.ndarray, attr, None)
263
+ numpy_object = getattr(np.ndarray, attr)
264
+ else:
265
+ cupy_object = None
266
+ numpy_object = getattr(self._numpy_array.__class__, attr)
267
+
268
+ if not callable(numpy_object):
269
+ if self._supports_cupy:
270
+ if self._remember_numpy:
271
+ self._update_cupy_array()
272
+ return getattr(self._cupy_array, attr)
273
+ return getattr(self._numpy_array, attr)
274
+
275
+ return _RecursiveAttr(numpy_object, cupy_object, self)
276
+
277
+ def _get_cupy_array(self):
278
+ """
279
+ Returns _cupy_array (cupy.ndarray) of ndarray object. And marks
280
+ self(ndarray) and it's base (if exist) as numpy not up-to-date.
281
+ """
282
+ base = self.base
283
+ if base is not None:
284
+ base._remember_numpy = False
285
+ self._remember_numpy = False
286
+ return self._cupy_array
287
+
288
+ def _get_numpy_array(self):
289
+ """
290
+ Returns _numpy_array (ex: np.ndarray, numpy.ma.MaskedArray,
291
+ numpy.chararray etc.) of ndarray object. And marks self(ndarray)
292
+ and it's base (if exist) as numpy up-to-date.
293
+ """
294
+ base = self.base
295
+ if base is not None and base._supports_cupy:
296
+ base._remember_numpy = True
297
+ if self._supports_cupy:
298
+ self._remember_numpy = True
299
+ return self._numpy_array
300
+
301
+ def _update_numpy_array(self):
302
+ """
303
+ Updates _numpy_array from _cupy_array.
304
+ To be executed before calling numpy function.
305
+ """
306
+ base = self.base
307
+ _type = np.ndarray if self._supports_cupy \
308
+ else self._numpy_array.__class__
309
+
310
+ if self._supports_cupy:
311
+ # cupy-compatible
312
+ if base is None:
313
+ if not self._remember_numpy:
314
+ if self._numpy_array is None:
315
+ self._numpy_array = cp.asnumpy(self._cupy_array)
316
+ else:
317
+ self._cupy_array.get(out=self._numpy_array)
318
+ else:
319
+ if not base._remember_numpy:
320
+ base._update_numpy_array()
321
+ if self._numpy_array is None:
322
+ self._numpy_array = base._numpy_array.view(type=_type)
323
+ self._numpy_array.shape = self._cupy_array.shape
324
+ self._numpy_array.strides = self._cupy_array.strides
325
+ else:
326
+ # not cupy-compatible
327
+ if base is not None:
328
+ assert base._supports_cupy
329
+ if not base._remember_numpy:
330
+ base._update_numpy_array()
331
+
332
+ def _update_cupy_array(self):
333
+ """
334
+ Updates _cupy_array from _numpy_array.
335
+ To be executed before calling cupy function.
336
+ """
337
+ base = self.base
338
+
339
+ if base is None:
340
+ if self._remember_numpy:
341
+ if self._cupy_array is None:
342
+ self._cupy_array = cp.array(self._numpy_array)
343
+ else:
344
+ self._cupy_array[:] = self._numpy_array
345
+ else:
346
+ if base._remember_numpy:
347
+ base._update_cupy_array()
348
+
349
+
350
+ def _create_magic_methods():
351
+ """
352
+ Set magic methods of cupy.ndarray as methods of fallback.ndarray.
353
+ """
354
+
355
+ # Decorator for ndarray magic methods
356
+ def make_method(name):
357
+ def method(self, *args, **kwargs):
358
+ CLASS = cp.ndarray if self._supports_cupy \
359
+ else self._numpy_array.__class__
360
+ _method = getattr(CLASS, name)
361
+ args = ((self,) + args)
362
+ if self._supports_cupy:
363
+ return _call_cupy(_method, args, kwargs)
364
+ return _call_numpy(_method, args, kwargs)
365
+ method.__doc__ = getattr(np.ndarray, name).__doc__
366
+ return method
367
+
368
+ for method in (
369
+ # Comparison operators:
370
+ '__eq__', '__ne__', '__lt__', '__gt__', '__le__', '__ge__',
371
+
372
+ # Unary operations:
373
+ '__neg__', '__pos__', '__abs__', '__invert__',
374
+
375
+ # Arithmetic:
376
+ '__add__', '__sub__', '__mul__', '__truediv__', '__floordiv__',
377
+ '__mod__', '__divmod__', '__pow__', '__lshift__', '__rshift__',
378
+ '__and__', '__or__', '__xor__',
379
+
380
+ # Arithmetic, in-place:
381
+ '__iadd__', '__isub__', '__imul__', '__itruediv__', '__ifloordiv__',
382
+ '__imod__', '__ipow__', '__ilshift__', '__irshift__',
383
+ '__iand__', '__ior__', '__ixor__',
384
+ '__matmul__',
385
+
386
+ # reflected-methods:
387
+ '__radd__', '__rsub__', '__rmul__', '__rtruediv__', '__rfloordiv__',
388
+ '__rmod__', '__rdivmod__', '__rpow__', '__rlshift__', '__rrshift__',
389
+ '__rand__', '__ror__', '__rxor__',
390
+ '__rmatmul__',
391
+
392
+ # For standard library functions:
393
+ '__copy__', '__deepcopy__', '__reduce__',
394
+
395
+ # Container customization:
396
+ '__iter__', '__len__', '__getitem__', '__setitem__',
397
+
398
+ # Conversion:
399
+ '__bool__', '__int__', '__float__', '__complex__',
400
+
401
+ # String representations:
402
+ '__repr__', '__str__'
403
+ ):
404
+ setattr(ndarray, method, make_method(method))
405
+
406
+
407
+ _create_magic_methods()
408
+
409
+
410
+ class vectorize(object):
411
+
412
+ __doc__ = np.vectorize.__doc__
413
+
414
+ def __init__(self, *args, **kwargs):
415
+ # NumPy will raise error if pyfunc is a cupy method
416
+ self.__dict__['_is_numpy_pyfunc'] = False
417
+ self.__dict__['_cupy_support'] = False
418
+ if isinstance(args[0], _RecursiveAttr):
419
+ self.__dict__['_is_numpy_pyfunc'] = True
420
+ if args[0]._cupy_object:
421
+ self.__dict__['_cupy_support'] = True
422
+ args = (args[0]._numpy_object,) + args[1:]
423
+ notification._dispatch_notification(np.vectorize)
424
+ self.__dict__['vec_obj'] = np.vectorize(*args, **kwargs)
425
+ self.__dict__['__doc__'] = self.__dict__['vec_obj'].__doc__
426
+
427
+ def __getattr__(self, attr):
428
+ return getattr(self.__dict__['vec_obj'], attr)
429
+
430
+ def __setattr__(self, name, value):
431
+ return setattr(self.vec_obj, name, value)
432
+
433
+ def __call__(self, *args, **kwargs):
434
+ if self._is_numpy_pyfunc:
435
+ notification._dispatch_notification(
436
+ self.vec_obj.pyfunc, self._cupy_support)
437
+ return _call_numpy(self.vec_obj, args, kwargs)
438
+
439
+
440
+ # -----------------------------------------------------------------------------
441
+ # Data Transfer methods
442
+ # -----------------------------------------------------------------------------
443
+
444
+
445
+ def _get_xp_args(ndarray_instance, to_xp, arg):
446
+ """
447
+ Converts ndarray_instance type object to target object using to_xp.
448
+
449
+ Args:
450
+ ndarray_instance (numpy.ndarray, cupy.ndarray or fallback.ndarray):
451
+ Objects of type `ndarray_instance` will be converted using `to_xp`.
452
+ to_xp (FunctionType): Method to convert ndarray_instance type objects.
453
+ arg (object): `ndarray_instance`, `tuple`, `list` and `dict` type
454
+ objects will be returned by either converting the object or it's
455
+ elements, if object is iterable. Objects of other types is
456
+ returned as it is.
457
+
458
+ Returns:
459
+ Return data structure will be same as before after converting ndarrays.
460
+ """
461
+
462
+ if isinstance(arg, ndarray_instance):
463
+ return to_xp(arg)
464
+
465
+ if isinstance(arg, tuple):
466
+ return tuple([_get_xp_args(ndarray_instance, to_xp, x) for x in arg])
467
+
468
+ if isinstance(arg, dict):
469
+ return {x_name: _get_xp_args(ndarray_instance, to_xp, x)
470
+ for x_name, x in arg.items()}
471
+
472
+ if isinstance(arg, list):
473
+ return [_get_xp_args(ndarray_instance, to_xp, x) for x in arg]
474
+
475
+ return arg
476
+
477
+
478
+ def _convert_numpy_to_fallback(numpy_res):
479
+ return _get_xp_args(np.ndarray, ndarray._store_array_from_numpy, numpy_res)
480
+
481
+
482
+ def _convert_fallback_to_numpy(args, kwargs):
483
+ return _get_xp_args(ndarray, ndarray._get_numpy_array, (args, kwargs))
484
+
485
+
486
+ def _convert_fallback_to_cupy(args, kwargs):
487
+ return _get_xp_args(ndarray, ndarray._get_cupy_array, (args, kwargs))
488
+
489
+
490
+ def _convert_cupy_to_fallback(cupy_res):
491
+ return _get_xp_args(cp.ndarray, ndarray._store_array_from_cupy, cupy_res)
492
+
493
+
494
+ def _update_numpy_args(args, kwargs):
495
+ return _get_xp_args(ndarray, ndarray._update_numpy_array, (args, kwargs))
496
+
497
+
498
+ def _update_cupy_args(args, kwargs):
499
+ return _get_xp_args(ndarray, ndarray._update_cupy_array, (args, kwargs))
500
+
501
+
502
+ # -----------------------------------------------------------------------------
503
+ # utils
504
+ # -----------------------------------------------------------------------------
505
+
506
+
507
+ def _call_cupy(func, args, kwargs):
508
+ """
509
+ Calls cupy function with *args and **kwargs and
510
+ does necessary data transfers.
511
+
512
+ Args:
513
+ func: A cupy function that needs to be called.
514
+ args (tuple): Arguments.
515
+ kwargs (dict): Keyword arguments.
516
+
517
+ Returns:
518
+ Result after calling func and performing data transfers.
519
+ """
520
+
521
+ _update_cupy_args(args, kwargs)
522
+ cupy_args, cupy_kwargs = _convert_fallback_to_cupy(args, kwargs)
523
+ cupy_res = func(*cupy_args, **cupy_kwargs)
524
+
525
+ # If existing argument is being returned
526
+ ext_res = _get_same_reference(
527
+ cupy_res, cupy_args, cupy_kwargs, args, kwargs)
528
+ if ext_res is not None:
529
+ return ext_res
530
+
531
+ if isinstance(cupy_res, cp.ndarray):
532
+ if cupy_res.base is None:
533
+ # Don't share memory
534
+ fallback_res = _convert_cupy_to_fallback(cupy_res)
535
+ else:
536
+ # Share memory with one of the arguments
537
+ base_arg = _get_same_reference(
538
+ cupy_res.base, cupy_args, cupy_kwargs, args, kwargs)
539
+ fallback_res = _convert_cupy_to_fallback(cupy_res)
540
+ fallback_res.base = base_arg
541
+ return fallback_res
542
+ return cupy_res
543
+
544
+
545
+ def _call_numpy(func, args, kwargs):
546
+ """
547
+ Calls numpy function with *args and **kwargs and
548
+ does necessary data transfers.
549
+
550
+ Args:
551
+ func: A numpy function that needs to be called.
552
+ args (tuple): Arguments.
553
+ kwargs (dict): Keyword arguments.
554
+
555
+ Returns:
556
+ Result after calling func and performing data transfers.
557
+ """
558
+
559
+ _update_numpy_args(args, kwargs)
560
+ numpy_args, numpy_kwargs = _convert_fallback_to_numpy(args, kwargs)
561
+ numpy_res = func(*numpy_args, **numpy_kwargs)
562
+
563
+ # If existing argument is being returned
564
+ ext_res = _get_same_reference(
565
+ numpy_res, numpy_args, numpy_kwargs, args, kwargs)
566
+ if ext_res is not None:
567
+ return ext_res
568
+
569
+ if isinstance(numpy_res, np.ndarray):
570
+ if numpy_res.base is None:
571
+ # Don't share memory
572
+ fallback_res = _convert_numpy_to_fallback(numpy_res)
573
+ else:
574
+ # Share memory with one of the arguments
575
+ base_arg = _get_same_reference(
576
+ numpy_res.base, numpy_args, numpy_kwargs, args, kwargs)
577
+ fallback_res = _convert_numpy_to_fallback(numpy_res)
578
+ fallback_res.base = base_arg
579
+ return fallback_res
580
+ return numpy_res
581
+
582
+
583
+ def _get_same_reference(res, args, kwargs, ret_args, ret_kwargs):
584
+ """
585
+ Returns object corresponding to res in (args, kwargs)
586
+ from (ret_args, ret_kwargs)
587
+ """
588
+ for i in range(len(args)):
589
+ if res is args[i]:
590
+ return ret_args[i]
591
+
592
+ for key in kwargs:
593
+ if res is kwargs[key]:
594
+ return ret_kwargs[key]
595
+
596
+ return
vllm/lib/python3.10/site-packages/cupyx/fallback_mode/notification.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Methods related to notifications.
3
+ """
4
+
5
+ import warnings
6
+
7
+ from cupyx import _ufunc_config
8
+
9
+
10
+ def _init_warnings():
11
+ FallbackWarning = type('FallbackWarning', (Warning,), {})
12
+ warnings.simplefilter(action='always', category=FallbackWarning)
13
+ return FallbackWarning
14
+
15
+
16
+ def _dispatch_notification(func, cupy_support=False):
17
+ """
18
+ Dispatch notifications using appropriate dispatch type.
19
+ """
20
+
21
+ dispatch_type = _ufunc_config.get_config_fallback_mode()
22
+
23
+ _module = getattr(func, '__module__', None)
24
+ _name = getattr(func, '__name__', None)
25
+
26
+ if not cupy_support:
27
+ if _name and _module:
28
+ msg = "'{}' method not in cupy, falling back to '{}.{}'".format(
29
+ _name, _module, _name)
30
+ elif _name:
31
+ msg = "'{}' method not in cupy, ".format(_name)
32
+ msg += "falling back to its numpy implementation"
33
+ else:
34
+ msg = "This method is not available in cupy, "
35
+ msg += "falling back to numpy"
36
+
37
+ if _name:
38
+ raise_msg = "'{}' method not found in cupy".format(_name)
39
+ else:
40
+ raise_msg = "This method is not available in cupy"
41
+ else:
42
+ if _name and _module:
43
+ msg = "'{}' method is available in cupy but ".format(_name)
44
+ msg += "cannot be used, falling back to '{}.{}'".format(
45
+ _module, _name)
46
+ elif _name:
47
+ msg = "'{}' method is available in cupy but ".format(_name)
48
+ msg += "cannot be used, falling back to its numpy implementation"
49
+ else:
50
+ msg = "This method is available in cupy, but cannot be used"
51
+ msg += "falling back to numpy"
52
+
53
+ if _name:
54
+ raise_msg = "'{}' method is available in cupy ".format(_name)
55
+ raise_msg += "but cannot be used"
56
+ else:
57
+ raise_msg = "This method is available in cupy but cannot be used"
58
+
59
+ if dispatch_type == 'print':
60
+ print("Warning: {}".format(msg))
61
+
62
+ elif dispatch_type == 'warn':
63
+ warnings.warn(msg, FallbackWarning, stacklevel=3)
64
+
65
+ elif dispatch_type == 'ignore':
66
+ pass
67
+
68
+ elif dispatch_type == 'raise':
69
+ raise AttributeError(raise_msg)
70
+
71
+ else:
72
+ assert False
73
+
74
+
75
+ FallbackWarning = _init_warnings()
vllm/lib/python3.10/site-packages/cupyx/lapack.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as _numpy
2
+
3
+ import cupy as _cupy
4
+ from cupy_backends.cuda.libs import cublas as _cublas
5
+ from cupy.cuda import device as _device
6
+
7
+
8
+ def gesv(a, b):
9
+ """Solve a linear matrix equation using cusolverDn<t>getr[fs]().
10
+
11
+ Computes the solution to a system of linear equation ``ax = b``.
12
+
13
+ Args:
14
+ a (cupy.ndarray): The matrix with dimension ``(M, M)``.
15
+ b (cupy.ndarray): The matrix with dimension ``(M)`` or ``(M, K)``.
16
+
17
+ Returns:
18
+ cupy.ndarray:
19
+ The matrix with dimension ``(M)`` or ``(M, K)``.
20
+
21
+ Note: ``a`` and ``b`` will be overwritten.
22
+ """
23
+ from cupy_backends.cuda.libs import cusolver as _cusolver
24
+
25
+ if a.ndim != 2:
26
+ raise ValueError('a.ndim must be 2 (actual: {})'.format(a.ndim))
27
+ if b.ndim not in (1, 2):
28
+ raise ValueError('b.ndim must be 1 or 2 (actual: {})'.format(b.ndim))
29
+ if a.shape[0] != a.shape[1]:
30
+ raise ValueError('a must be a square matrix.')
31
+ if a.shape[0] != b.shape[0]:
32
+ raise ValueError('shape mismatch (a: {}, b: {}).'.
33
+ format(a.shape, b.shape))
34
+ if a.dtype != b.dtype:
35
+ raise TypeError('dtype mismatch (a: {}, b: {})'.
36
+ format(a.dtype, b.dtype))
37
+ dtype = a.dtype
38
+ if dtype == 'f':
39
+ t = 's'
40
+ elif dtype == 'd':
41
+ t = 'd'
42
+ elif dtype == 'F':
43
+ t = 'c'
44
+ elif dtype == 'D':
45
+ t = 'z'
46
+ else:
47
+ raise TypeError('unsupported dtype (actual:{})'.format(a.dtype))
48
+ helper = getattr(_cusolver, t + 'getrf_bufferSize')
49
+ getrf = getattr(_cusolver, t + 'getrf')
50
+ getrs = getattr(_cusolver, t + 'getrs')
51
+
52
+ n = b.shape[0]
53
+ nrhs = b.shape[1] if b.ndim == 2 else 1
54
+ if a._f_contiguous:
55
+ trans = _cublas.CUBLAS_OP_N
56
+ elif a._c_contiguous:
57
+ trans = _cublas.CUBLAS_OP_T
58
+ else:
59
+ raise ValueError('a must be F-contiguous or C-contiguous.')
60
+ if not b._f_contiguous:
61
+ raise ValueError('b must be F-contiguous.')
62
+
63
+ handle = _device.get_cusolver_handle()
64
+ dipiv = _cupy.empty(n, dtype=_numpy.int32)
65
+ dinfo = _cupy.empty(1, dtype=_numpy.int32)
66
+ lwork = helper(handle, n, n, a.data.ptr, n)
67
+ dwork = _cupy.empty(lwork, dtype=a.dtype)
68
+ # LU factrization (A = L * U)
69
+ getrf(handle, n, n, a.data.ptr, n, dwork.data.ptr, dipiv.data.ptr,
70
+ dinfo.data.ptr)
71
+ _cupy.linalg._util._check_cusolver_dev_info_if_synchronization_allowed(
72
+ getrf, dinfo)
73
+ # Solves Ax = b
74
+ getrs(handle, trans, n, nrhs, a.data.ptr, n,
75
+ dipiv.data.ptr, b.data.ptr, n, dinfo.data.ptr)
76
+ _cupy.linalg._util._check_cusolver_dev_info_if_synchronization_allowed(
77
+ getrs, dinfo)
78
+
79
+
80
+ def gels(a, b):
81
+ """Solves over/well/under-determined linear systems.
82
+
83
+ Computes least-square solution to equation ``ax = b` by QR factorization
84
+ using cusolverDn<t>geqrf().
85
+
86
+ Args:
87
+ a (cupy.ndarray): The matrix with dimension ``(M, N)``.
88
+ b (cupy.ndarray): The matrix with dimension ``(M)`` or ``(M, K)``.
89
+
90
+ Returns:
91
+ cupy.ndarray:
92
+ The matrix with dimension ``(N)`` or ``(N, K)``.
93
+ """
94
+ from cupy_backends.cuda.libs import cusolver as _cusolver
95
+
96
+ if a.ndim != 2:
97
+ raise ValueError('a.ndim must be 2 (actual: {})'.format(a.ndim))
98
+ if b.ndim == 1:
99
+ nrhs = 1
100
+ elif b.ndim == 2:
101
+ nrhs = b.shape[1]
102
+ else:
103
+ raise ValueError('b.ndim must be 1 or 2 (actual: {})'.format(b.ndim))
104
+ if a.shape[0] != b.shape[0]:
105
+ raise ValueError('shape mismatch (a: {}, b: {}).'.
106
+ format(a.shape, b.shape))
107
+ if a.dtype != b.dtype:
108
+ raise ValueError('dtype mismatch (a: {}, b: {}).'.
109
+ format(a.dtype, b.dtype))
110
+
111
+ dtype = a.dtype
112
+ if dtype == 'f':
113
+ t = 's'
114
+ elif dtype == 'd':
115
+ t = 'd'
116
+ elif dtype == 'F':
117
+ t = 'c'
118
+ elif dtype == 'D':
119
+ t = 'z'
120
+ else:
121
+ raise ValueError('unsupported dtype (actual: {})'.format(dtype))
122
+
123
+ geqrf_helper = getattr(_cusolver, t + 'geqrf_bufferSize')
124
+ geqrf = getattr(_cusolver, t + 'geqrf')
125
+ trsm = getattr(_cublas, t + 'trsm')
126
+ if t in 'sd':
127
+ ormqr_helper = getattr(_cusolver, t + 'ormqr_bufferSize')
128
+ ormqr = getattr(_cusolver, t + 'ormqr')
129
+ else:
130
+ ormqr_helper = getattr(_cusolver, t + 'unmqr_bufferSize')
131
+ ormqr = getattr(_cusolver, t + 'unmqr')
132
+
133
+ no_trans = _cublas.CUBLAS_OP_N
134
+ if dtype.char in 'fd':
135
+ trans = _cublas.CUBLAS_OP_T
136
+ else:
137
+ trans = _cublas.CUBLAS_OP_C
138
+
139
+ m, n = a.shape
140
+ mn_min = min(m, n)
141
+ dev_info = _cupy.empty(1, dtype=_numpy.int32)
142
+ tau = _cupy.empty(mn_min, dtype=dtype)
143
+ cusolver_handle = _device.get_cusolver_handle()
144
+ cublas_handle = _device.get_cublas_handle()
145
+ one = _numpy.array(1.0, dtype=dtype)
146
+
147
+ if m >= n: # over/well-determined systems
148
+ a = a.copy(order='F')
149
+ b = b.copy(order='F')
150
+
151
+ # geqrf (QR decomposition, A = Q * R)
152
+ ws_size = geqrf_helper(cusolver_handle, m, n, a.data.ptr, m)
153
+ workspace = _cupy.empty(ws_size, dtype=dtype)
154
+ geqrf(cusolver_handle, m, n, a.data.ptr, m, tau.data.ptr,
155
+ workspace.data.ptr, ws_size, dev_info.data.ptr)
156
+ _cupy.linalg._util._check_cusolver_dev_info_if_synchronization_allowed(
157
+ geqrf, dev_info)
158
+
159
+ # ormqr (Computes Q^T * B)
160
+ ws_size = ormqr_helper(
161
+ cusolver_handle, _cublas.CUBLAS_SIDE_LEFT, trans, m, nrhs, mn_min,
162
+ a.data.ptr, m, tau.data.ptr, b.data.ptr, m)
163
+ workspace = _cupy.empty(ws_size, dtype=dtype)
164
+ ormqr(cusolver_handle, _cublas.CUBLAS_SIDE_LEFT, trans, m, nrhs,
165
+ mn_min, a.data.ptr, m, tau.data.ptr, b.data.ptr, m,
166
+ workspace.data.ptr, ws_size, dev_info.data.ptr)
167
+ _cupy.linalg._util._check_cusolver_dev_info_if_synchronization_allowed(
168
+ ormqr, dev_info)
169
+
170
+ # trsm (Solves R * X = (Q^T * B))
171
+ trsm(cublas_handle, _cublas.CUBLAS_SIDE_LEFT,
172
+ _cublas.CUBLAS_FILL_MODE_UPPER, no_trans,
173
+ _cublas.CUBLAS_DIAG_NON_UNIT, mn_min, nrhs,
174
+ one.ctypes.data, a.data.ptr, m, b.data.ptr, m)
175
+
176
+ return b[:n]
177
+
178
+ else: # under-determined systems
179
+ a = a.conj().T.copy(order='F')
180
+ bb = b
181
+ out_shape = (n,) if b.ndim == 1 else (n, nrhs)
182
+ b = _cupy.zeros(out_shape, dtype=dtype, order='F')
183
+ b[:m] = bb
184
+
185
+ # geqrf (QR decomposition, A^T = Q * R)
186
+ ws_size = geqrf_helper(cusolver_handle, n, m, a.data.ptr, n)
187
+ workspace = _cupy.empty(ws_size, dtype=dtype)
188
+ geqrf(cusolver_handle, n, m, a.data.ptr, n, tau.data.ptr,
189
+ workspace.data.ptr, ws_size, dev_info.data.ptr)
190
+ _cupy.linalg._util._check_cusolver_dev_info_if_synchronization_allowed(
191
+ geqrf, dev_info)
192
+
193
+ # trsm (Solves R^T * Z = B)
194
+ trsm(cublas_handle, _cublas.CUBLAS_SIDE_LEFT,
195
+ _cublas.CUBLAS_FILL_MODE_UPPER, trans,
196
+ _cublas.CUBLAS_DIAG_NON_UNIT, m, nrhs,
197
+ one.ctypes.data, a.data.ptr, n, b.data.ptr, n)
198
+
199
+ # ormqr (Computes Q * Z)
200
+ ws_size = ormqr_helper(
201
+ cusolver_handle, _cublas.CUBLAS_SIDE_LEFT, no_trans, n, nrhs,
202
+ mn_min, a.data.ptr, n, tau.data.ptr, b.data.ptr, n)
203
+ workspace = _cupy.empty(ws_size, dtype=dtype)
204
+ ormqr(cusolver_handle, _cublas.CUBLAS_SIDE_LEFT, no_trans, n, nrhs,
205
+ mn_min, a.data.ptr, n, tau.data.ptr, b.data.ptr, n,
206
+ workspace.data.ptr, ws_size, dev_info.data.ptr)
207
+ _cupy.linalg._util._check_cusolver_dev_info_if_synchronization_allowed(
208
+ ormqr, dev_info)
209
+
210
+ return b
211
+
212
+
213
+ def _batched_posv(a, b):
214
+ from cupy_backends.cuda.libs import cusolver as _cusolver
215
+ import cupyx.cusolver
216
+
217
+ if not cupyx.cusolver.check_availability('potrsBatched'):
218
+ raise RuntimeError('potrsBatched is not available')
219
+
220
+ dtype = _numpy.promote_types(a.dtype, b.dtype)
221
+ dtype = _numpy.promote_types(dtype, 'f')
222
+
223
+ if dtype == 'f':
224
+ potrfBatched = _cusolver.spotrfBatched
225
+ potrsBatched = _cusolver.spotrsBatched
226
+ elif dtype == 'd':
227
+ potrfBatched = _cusolver.dpotrfBatched
228
+ potrsBatched = _cusolver.dpotrsBatched
229
+ elif dtype == 'F':
230
+ potrfBatched = _cusolver.cpotrfBatched
231
+ potrsBatched = _cusolver.cpotrsBatched
232
+ elif dtype == 'D':
233
+ potrfBatched = _cusolver.zpotrfBatched
234
+ potrsBatched = _cusolver.zpotrsBatched
235
+ else:
236
+ msg = ('dtype must be float32, float64, complex64 or complex128'
237
+ ' (actual: {})'.format(a.dtype))
238
+ raise ValueError(msg)
239
+
240
+ a = a.astype(dtype, order='C', copy=True)
241
+ ap = _cupy._core._mat_ptrs(a)
242
+ lda, n = a.shape[-2:]
243
+ batch_size = int(_numpy.prod(a.shape[:-2]))
244
+
245
+ handle = _device.get_cusolver_handle()
246
+ uplo = _cublas.CUBLAS_FILL_MODE_LOWER
247
+ dev_info = _cupy.empty(batch_size, dtype=_numpy.int32)
248
+
249
+ # Cholesky factorization
250
+ potrfBatched(handle, uplo, n, ap.data.ptr, lda, dev_info.data.ptr,
251
+ batch_size)
252
+ _cupy.linalg._util._check_cusolver_dev_info_if_synchronization_allowed(
253
+ potrfBatched, dev_info)
254
+
255
+ b_shape = b.shape
256
+ b = b.conj().reshape(batch_size, n, -1).astype(dtype, order='C', copy=True)
257
+ bp = _cupy._core._mat_ptrs(b)
258
+ ldb, nrhs = b.shape[-2:]
259
+ dev_info = _cupy.empty(1, dtype=_numpy.int32)
260
+
261
+ # NOTE: potrsBatched does not currently support nrhs > 1 (CUDA v10.2)
262
+ # Solve: A[i] * X[i] = B[i]
263
+ potrsBatched(handle, uplo, n, nrhs, ap.data.ptr, lda, bp.data.ptr, ldb,
264
+ dev_info.data.ptr, batch_size)
265
+ _cupy.linalg._util._check_cusolver_dev_info_if_synchronization_allowed(
266
+ potrsBatched, dev_info)
267
+
268
+ # TODO: check if conj() is necessary when nrhs > 1
269
+ return b.conj().reshape(b_shape)
270
+
271
+
272
+ def posv(a, b):
273
+ """Solve the linear equations A x = b via Cholesky factorization of A,
274
+ where A is a real symmetric or complex Hermitian positive-definite matrix.
275
+
276
+ If matrix ``A`` is not positive definite, Cholesky factorization fails
277
+ and it raises an error.
278
+
279
+ Note: For batch input, NRHS > 1 is not currently supported.
280
+
281
+ Args:
282
+ a (cupy.ndarray): Array of real symmetric or complex hermitian
283
+ matrices with dimension (..., N, N).
284
+ b (cupy.ndarray): right-hand side (..., N) or (..., N, NRHS).
285
+ Returns:
286
+ x (cupy.ndarray): The solution (shape matches b).
287
+ """
288
+ from cupy_backends.cuda.libs import cusolver as _cusolver
289
+
290
+ _util = _cupy.linalg._util
291
+ _util._assert_cupy_array(a, b)
292
+ _util._assert_stacked_2d(a)
293
+ _util._assert_stacked_square(a)
294
+
295
+ if a.ndim > 2:
296
+ return _batched_posv(a, b)
297
+
298
+ dtype = _numpy.promote_types(a.dtype, b.dtype)
299
+ dtype = _numpy.promote_types(dtype, 'f')
300
+
301
+ if dtype == 'f':
302
+ potrf = _cusolver.spotrf
303
+ potrf_bufferSize = _cusolver.spotrf_bufferSize
304
+ potrs = _cusolver.spotrs
305
+ elif dtype == 'd':
306
+ potrf = _cusolver.dpotrf
307
+ potrf_bufferSize = _cusolver.dpotrf_bufferSize
308
+ potrs = _cusolver.dpotrs
309
+ elif dtype == 'F':
310
+ potrf = _cusolver.cpotrf
311
+ potrf_bufferSize = _cusolver.cpotrf_bufferSize
312
+ potrs = _cusolver.cpotrs
313
+ elif dtype == 'D':
314
+ potrf = _cusolver.zpotrf
315
+ potrf_bufferSize = _cusolver.zpotrf_bufferSize
316
+ potrs = _cusolver.zpotrs
317
+ else:
318
+ msg = ('dtype must be float32, float64, complex64 or complex128'
319
+ ' (actual: {})'.format(a.dtype))
320
+ raise ValueError(msg)
321
+
322
+ a = a.astype(dtype, order='F', copy=True)
323
+ lda, n = a.shape
324
+
325
+ handle = _device.get_cusolver_handle()
326
+ uplo = _cublas.CUBLAS_FILL_MODE_LOWER
327
+ dev_info = _cupy.empty(1, dtype=_numpy.int32)
328
+
329
+ worksize = potrf_bufferSize(handle, uplo, n, a.data.ptr, lda)
330
+ workspace = _cupy.empty(worksize, dtype=dtype)
331
+
332
+ # Cholesky factorization
333
+ potrf(handle, uplo, n, a.data.ptr, lda, workspace.data.ptr,
334
+ worksize, dev_info.data.ptr)
335
+ _cupy.linalg._util._check_cusolver_dev_info_if_synchronization_allowed(
336
+ potrf, dev_info)
337
+
338
+ b_shape = b.shape
339
+ b = b.reshape(n, -1).astype(dtype, order='F', copy=True)
340
+ ldb, nrhs = b.shape
341
+
342
+ # Solve: A * X = B
343
+ potrs(handle, uplo, n, nrhs, a.data.ptr, lda, b.data.ptr, ldb,
344
+ dev_info.data.ptr)
345
+ _cupy.linalg._util._check_cusolver_dev_info_if_synchronization_allowed(
346
+ potrs, dev_info)
347
+
348
+ return _cupy.ascontiguousarray(b.reshape(b_shape))
vllm/lib/python3.10/site-packages/cupyx/optimizing/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from cupyx.optimizing._optimize import optimize # NOQA
vllm/lib/python3.10/site-packages/cupyx/optimizing/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (225 Bytes). View file
 
vllm/lib/python3.10/site-packages/cupyx/optimizing/__pycache__/_optimize.cpython-310.pyc ADDED
Binary file (3.54 kB). View file
 
vllm/lib/python3.10/site-packages/cupyx/optimizing/_optimize.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import math
3
+ import os
4
+ import warnings
5
+
6
+
7
+ try:
8
+ import optuna
9
+ _optuna_available = True
10
+ except ImportError:
11
+ _optuna_available = False
12
+
13
+
14
+ from cupy._core import _optimize_config
15
+ from cupyx import profiler
16
+
17
+
18
+ def _optimize(
19
+ optimize_config, target_func, suggest_func,
20
+ default_best, ignore_error=()):
21
+ assert isinstance(optimize_config, _optimize_config._OptimizationConfig)
22
+ assert callable(target_func)
23
+ assert callable(suggest_func)
24
+
25
+ def objective(trial):
26
+ args = suggest_func(trial)
27
+ max_total_time = optimize_config.max_total_time_per_trial
28
+ try:
29
+ perf = profiler.benchmark(
30
+ target_func, args, max_duration=max_total_time)
31
+ return perf.gpu_times.mean()
32
+ except Exception as e:
33
+ if isinstance(e, ignore_error):
34
+ return math.inf
35
+ else:
36
+ raise e
37
+
38
+ study = optuna.create_study()
39
+ study.enqueue_trial(default_best)
40
+ study.optimize(
41
+ objective,
42
+ n_trials=optimize_config.max_trials,
43
+ timeout=optimize_config.timeout)
44
+ return study.best_trial
45
+
46
+
47
+ @contextlib.contextmanager
48
+ def optimize(*, key=None, path=None, readonly=False, **config_dict):
49
+ """Context manager that optimizes kernel launch parameters.
50
+
51
+ In this context, CuPy's routines find the best kernel launch parameter
52
+ values (e.g., the number of threads and blocks). The found values are
53
+ cached and reused with keys as the shapes, strides and dtypes of the
54
+ given inputs arrays.
55
+
56
+ Args:
57
+ key (string or None): The cache key of optimizations.
58
+ path (string or None): The path to save optimization cache records.
59
+ When path is specified and exists, records will be loaded from
60
+ the path. When readonly option is set to ``False``, optimization
61
+ cache records will be saved to the path after the optimization.
62
+ readonly (bool): See the description of ``path`` option.
63
+ max_trials (int): The number of trials that defaults to 100.
64
+ timeout (float):
65
+ Stops study after the given number of seconds. Default is 1.
66
+ max_total_time_per_trial (float):
67
+ Repeats measuring the execution time of the routine for the
68
+ given number of seconds. Default is 0.1.
69
+
70
+ Examples
71
+ --------
72
+ >>> import cupy
73
+ >>> from cupyx import optimizing
74
+ >>>
75
+ >>> x = cupy.arange(100)
76
+ >>> with optimizing.optimize():
77
+ ... cupy.sum(x)
78
+ ...
79
+ array(4950)
80
+
81
+ .. note::
82
+ Optuna (https://optuna.org) installation is required.
83
+ Currently it works for reduction operations only.
84
+ """
85
+ if not _optuna_available:
86
+ raise RuntimeError(
87
+ 'Optuna is required to run optimization. '
88
+ 'See https://optuna.org/ for the installation instructions.')
89
+
90
+ old_context = _optimize_config.get_current_context()
91
+ context = _optimize_config.get_new_context(key, _optimize, config_dict)
92
+ _optimize_config.set_current_context(context)
93
+
94
+ if path is not None:
95
+ if os.path.exists(path):
96
+ context.load(path)
97
+ elif readonly:
98
+ warnings.warn('''
99
+ The specified path {} could not be found, and the readonly option is set.
100
+ The optimization results will never be stored.
101
+ '''.format(path))
102
+
103
+ try:
104
+ yield context
105
+ if path is not None and not readonly:
106
+ if context._is_dirty() or not os.path.exists(path):
107
+ context.save(path)
108
+ finally:
109
+ _optimize_config.set_current_context(old_context)
vllm/lib/python3.10/site-packages/cupyx/profiler/__init__.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib as _contextlib
2
+ from cupy.cuda import runtime as _runtime
3
+ from cupyx.profiler._time import benchmark # NOQA
4
+ from cupyx.profiler._time_range import time_range # NOQA
5
+
6
+
7
+ @_contextlib.contextmanager
8
+ def profile():
9
+ """Enable CUDA profiling during with statement.
10
+
11
+ This function enables profiling on entering a with statement, and disables
12
+ profiling on leaving the statement.
13
+
14
+ >>> with cupyx.profiler.profile():
15
+ ... # do something you want to measure
16
+ ... pass
17
+
18
+ .. note::
19
+ When starting ``nvprof`` from the command line, manually setting
20
+ ``--profile-from-start off`` may be required for the desired behavior.
21
+ Likewise, when using ``nsys profile`` setting ``-c cudaProfilerApi``
22
+ may be required.
23
+
24
+ .. seealso:: :func:`cupy.cuda.runtime.profilerStart`,
25
+ :func:`cupy.cuda.runtime.profilerStop`
26
+ """
27
+ _runtime.profilerStart()
28
+ try:
29
+ yield
30
+ finally:
31
+ _runtime.profilerStop()
vllm/lib/python3.10/site-packages/cupyx/profiler/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.22 kB). View file
 
vllm/lib/python3.10/site-packages/cupyx/profiler/__pycache__/_time.cpython-310.pyc ADDED
Binary file (7.13 kB). View file
 
vllm/lib/python3.10/site-packages/cupyx/profiler/__pycache__/_time_range.cpython-310.pyc ADDED
Binary file (3.19 kB). View file
 
vllm/lib/python3.10/site-packages/cupyx/profiler/_time.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math as _math
2
+ import time as _time
3
+
4
+ import numpy as _numpy
5
+
6
+ import cupy as _cupy
7
+ from cupy_backends.cuda.api import runtime
8
+
9
+
10
+ class _PerfCaseResult:
11
+ """ An obscure object encompassing timing results recorded by
12
+ :func:`~cupyx.profiler.benchmark`. Simple statistics can be obtained by
13
+ converting an instance of this class to a string.
14
+
15
+ .. warning::
16
+ This API is currently experimental and subject to change in future
17
+ releases.
18
+
19
+ """
20
+
21
+ def __init__(self, name, ts, devices):
22
+ assert ts.ndim == 2
23
+ assert ts.shape[0] == len(devices) + 1
24
+ assert ts.shape[1] > 0
25
+ self.name = name
26
+ self._ts = ts
27
+ self._devices = devices
28
+
29
+ def __repr__(self) -> str:
30
+ """ Returns a string representation of the object.
31
+
32
+ Returns:
33
+ str: A string representation of the object.
34
+ """
35
+ return self.to_str(show_gpu=True)
36
+
37
+ @property
38
+ def cpu_times(self) -> _numpy.ndarray:
39
+ """A :class:`numpy.ndarray` of shape ``(n_repeat,)``, holding times spent
40
+ on CPU in seconds.
41
+
42
+ These values are delta of the host-side performance counter
43
+ (:func:`time.perf_counter`) between each repeat step.
44
+ """ # NOQA
45
+ return self._ts[0]
46
+
47
+ @property
48
+ def gpu_times(self) -> _numpy.ndarray:
49
+ """A :class:`numpy.ndarray` of shape ``(len(devices), n_repeat)``,
50
+ holding times spent on GPU in seconds.
51
+
52
+ These values are measured using ``cudaEventElapsedTime`` with events
53
+ recoreded before/after each repeat step.
54
+ """
55
+ return self._ts[1:]
56
+
57
+ @staticmethod
58
+ def _to_str_per_item(device_name, t):
59
+ assert t.ndim == 1
60
+ assert t.size > 0
61
+ t_us = t * 1e6
62
+
63
+ s = ' {}: {:9.03f} us'.format(device_name, t_us.mean())
64
+ if t.size > 1:
65
+ s += ' +/- {:6.03f} (min: {:9.03f} / max: {:9.03f}) us'.format(
66
+ t_us.std(), t_us.min(), t_us.max())
67
+ return s
68
+
69
+ def to_str(self, show_gpu=False):
70
+ results = [self._to_str_per_item('CPU', self._ts[0])]
71
+ if show_gpu:
72
+ for i, d in enumerate(self._devices):
73
+ results.append(
74
+ self._to_str_per_item('GPU-{}'.format(d),
75
+ self._ts[1 + i]))
76
+ return '{:<20s}:{}'.format(self.name, ' '.join(results))
77
+
78
+ def __str__(self):
79
+ return self.to_str(show_gpu=True)
80
+
81
+
82
+ def benchmark(
83
+ func, args=(), kwargs={}, n_repeat=10000, *,
84
+ name=None, n_warmup=10, max_duration=_math.inf, devices=None):
85
+ """ Timing utility for measuring time spent by both CPU and GPU.
86
+
87
+ This function is a very convenient helper for setting up a timing test. The
88
+ GPU time is properly recorded by synchronizing internal streams. As a
89
+ result, to time a multi-GPU function all participating devices must be
90
+ passed as the ``devices`` argument so that this helper knows which devices
91
+ to record. A simple example is given as follows:
92
+
93
+ .. code-block:: py
94
+
95
+ import cupy as cp
96
+ from cupyx.profiler import benchmark
97
+
98
+ def f(a, b):
99
+ return 3 * cp.sin(-a) * b
100
+
101
+ a = 0.5 - cp.random.random((100,))
102
+ b = cp.random.random((100,))
103
+ print(benchmark(f, (a, b), n_repeat=1000))
104
+
105
+
106
+ Args:
107
+ func (callable): a callable object to be timed.
108
+ args (tuple): positional arguments to be passed to the callable.
109
+ kwargs (dict): keyword arguments to be passed to the callable.
110
+ n_repeat (int): number of times the callable is called. Increasing
111
+ this value would improve the collected statistics at the cost
112
+ of longer test time.
113
+ name (str): the function name to be reported. If not given, the
114
+ callable's ``__name__`` attribute is used.
115
+ n_warmup (int): number of times the callable is called. The warm-up
116
+ runs are not timed.
117
+ max_duration (float): the maximum time (in seconds) that the entire
118
+ test can use. If the taken time is longer than this limit, the test
119
+ is stopped and the statistics collected up to the breakpoint is
120
+ reported.
121
+ devices (tuple): a tuple of device IDs (int) that will be timed during
122
+ the timing test. If not given, the current device is used.
123
+
124
+ Returns:
125
+ :class:`~cupyx.profiler._time._PerfCaseResult`:
126
+ an object collecting all test results.
127
+
128
+ """
129
+
130
+ if name is None:
131
+ name = func.__name__
132
+
133
+ if devices is None:
134
+ devices = (_cupy.cuda.get_device_id(),)
135
+
136
+ if not callable(func):
137
+ raise ValueError('`func` should be a callable object.')
138
+ if not isinstance(args, tuple):
139
+ raise ValueError('`args` should be of tuple type.')
140
+ if not isinstance(kwargs, dict):
141
+ raise ValueError('`kwargs` should be of dict type.')
142
+ if not isinstance(n_repeat, int):
143
+ raise ValueError('`n_repeat` should be an integer.')
144
+ if not isinstance(name, str):
145
+ raise ValueError('`name` should be a string.')
146
+ if not isinstance(n_warmup, int):
147
+ raise ValueError('`n_warmup` should be an integer.')
148
+ if not _numpy.isreal(max_duration):
149
+ raise ValueError('`max_duration` should be given in seconds')
150
+ if not isinstance(devices, tuple):
151
+ raise ValueError('`devices` should be of tuple type')
152
+
153
+ return _repeat(
154
+ func, args, kwargs, n_repeat, name, n_warmup, max_duration, devices)
155
+
156
+
157
+ def _repeat(
158
+ func, args, kwargs, n_repeat, name, n_warmup, max_duration, devices):
159
+
160
+ events_1 = []
161
+ events_2 = []
162
+
163
+ for i in devices:
164
+ prev_device = runtime.getDevice()
165
+ try:
166
+ runtime.setDevice(i)
167
+ events_1.append(_cupy.cuda.stream.Event())
168
+ events_2.append(_cupy.cuda.stream.Event())
169
+ finally:
170
+ runtime.setDevice(prev_device)
171
+
172
+ for i in range(n_warmup):
173
+ func(*args, **kwargs)
174
+
175
+ for event, device in zip(events_1, devices):
176
+ prev_device = runtime.getDevice()
177
+ try:
178
+ runtime.setDevice(device)
179
+ event.record()
180
+ finally:
181
+ runtime.setDevice(prev_device)
182
+ event.synchronize()
183
+
184
+ cpu_times = []
185
+ gpu_times = [[] for i in events_1]
186
+ duration = 0
187
+ for i in range(n_repeat):
188
+ for event, device in zip(events_1, devices):
189
+ prev_device = runtime.getDevice()
190
+ try:
191
+ runtime.setDevice(device)
192
+ event.record()
193
+ finally:
194
+ runtime.setDevice(prev_device)
195
+
196
+ t1 = _time.perf_counter()
197
+
198
+ func(*args, **kwargs)
199
+
200
+ t2 = _time.perf_counter()
201
+ cpu_time = t2 - t1
202
+ cpu_times.append(cpu_time)
203
+
204
+ for event, device in zip(events_2, devices):
205
+ prev_device = runtime.getDevice()
206
+ try:
207
+ runtime.setDevice(device)
208
+ event.record()
209
+ finally:
210
+ runtime.setDevice(prev_device)
211
+ for event, device in zip(events_2, devices):
212
+ prev_device = runtime.getDevice()
213
+ try:
214
+ runtime.setDevice(device)
215
+ event.synchronize()
216
+ finally:
217
+ runtime.setDevice(prev_device)
218
+ for i, (ev1, ev2) in enumerate(zip(events_1, events_2)):
219
+ gpu_time = _cupy.cuda.get_elapsed_time(ev1, ev2) * 1e-3
220
+ gpu_times[i].append(gpu_time)
221
+
222
+ duration += _time.perf_counter() - t1
223
+ if duration > max_duration:
224
+ break
225
+
226
+ ts = _numpy.asarray([cpu_times] + gpu_times, dtype=_numpy.float64)
227
+ return _PerfCaseResult(name, ts, devices=devices)
vllm/lib/python3.10/site-packages/cupyx/profiler/_time_range.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+
3
+ from cupy import cuda
4
+ from cupy_backends.cuda.api import runtime
5
+
6
+
7
+ # Note: We use an (old-fashioned) custom object instead of
8
+ # @contextlib.contextmanager because for backward compatibility
9
+ # when used as a decorator this object needs to fetch the target
10
+ # function name.
11
+ class time_range:
12
+ """Mark function calls with ranges using NVTX/rocTX. This object can be
13
+ used either as a decorator or a context manager.
14
+
15
+ When used as a decorator, the decorated function calls are marked as
16
+ ranges:
17
+
18
+ >>> from cupyx.profiler import time_range
19
+ >>> @time_range()
20
+ ... def function_to_profile():
21
+ ... pass
22
+
23
+ When used as a context manager, it describes the enclosed block as a nested
24
+ range:
25
+
26
+ >>> from cupyx.profiler import time_range
27
+ >>> with time_range('some range in green', color_id=0):
28
+ ... # do something you want to measure
29
+ ... pass
30
+
31
+ The marked ranges are visible in the profiler (such as nvvp, nsys-ui, etc)
32
+ timeline.
33
+
34
+ Args:
35
+ message (str): Name of a range. When used as a decorator, the default
36
+ is ``func.__name__``.
37
+ color_id: range color ID
38
+ argb_color: range color in ARGB (e.g. 0xFF00FF00 for green)
39
+ sync (bool): If ``True``, waits for completion of all outstanding
40
+ processing on GPU before calling :func:`cupy.cuda.nvtx.RangePush()`
41
+ or :func:`cupy.cuda.nvtx.RangePop()`
42
+
43
+ .. seealso:: :func:`cupy.cuda.nvtx.RangePush`,
44
+ :func:`cupy.cuda.nvtx.RangePop`
45
+ """
46
+
47
+ def __init__(
48
+ self, message=None, color_id=None, argb_color=None, sync=False):
49
+ if not cuda.nvtx.available:
50
+ raise RuntimeError('nvtx is not installed')
51
+
52
+ if color_id is not None and argb_color is not None:
53
+ raise ValueError(
54
+ 'Only either color_id or argb_color can be specified'
55
+ )
56
+ self.message = message
57
+ self.color_id = color_id if color_id is not None else -1
58
+ self.argb_color = argb_color
59
+ self.sync = sync
60
+
61
+ def __enter__(self):
62
+ if self.message is None:
63
+ raise ValueError(
64
+ 'when used as a context manager, the message argument cannot '
65
+ 'be None')
66
+ if self.sync:
67
+ runtime.deviceSynchronize()
68
+ if self.argb_color is not None:
69
+ cuda.nvtx.RangePushC(self.message, self.argb_color)
70
+ else:
71
+ cuda.nvtx.RangePush(self.message, self.color_id)
72
+ return self
73
+
74
+ def __exit__(self, exc_type, exc_value, traceback):
75
+ if self.sync:
76
+ runtime.deviceSynchronize()
77
+ cuda.nvtx.RangePop()
78
+
79
+ def _recreate_cm(self, message):
80
+ if self.message is None:
81
+ self.message = message
82
+ return self
83
+
84
+ def __call__(self, func):
85
+ @functools.wraps(func)
86
+ def inner(*args, **kwargs):
87
+ with self._recreate_cm(func.__name__):
88
+ return func(*args, **kwargs)
89
+ return inner
vllm/lib/python3.10/site-packages/cupyx/signal/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from cupyx.signal._acoustics import complex_cepstrum, real_cepstrum # NOQA
2
+ from cupyx.signal._acoustics import inverse_complex_cepstrum # NOQA
3
+ from cupyx.signal._acoustics import minimum_phase # NOQA
4
+ from cupyx.signal._convolution import convolve1d2o # NOQA
5
+ from cupyx.signal._convolution import convolve1d3o # NOQA
6
+ from cupyx.signal._filtering import channelize_poly # NOQA
7
+ from cupyx.signal._filtering import firfilter, firfilter2, firfilter_zi # NOQA
8
+ from cupyx.signal._filtering import freq_shift # NOQA
9
+ from cupyx.signal._radartools import pulse_compression # NOQA
10
+ from cupyx.signal._radartools import pulse_doppler # NOQA
11
+ from cupyx.signal._radartools import cfar_alpha # NOQA
12
+ from cupyx.signal._radartools import ca_cfar # NOQA
13
+ from cupyx.signal._radartools import mvdr # NOQA
vllm/lib/python3.10/site-packages/cupyx/signal/_convolution/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from cupyx.signal._convolution._convolve import convolve1d2o # NOQA
2
+ from cupyx.signal._convolution._convolve import convolve1d3o # NOQA
vllm/lib/python3.10/site-packages/cupyx/signal/_convolution/_convolve.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Some of the functions defined here were ported directly from CuSignal under
3
+ terms of the MIT license, under the following notice:
4
+
5
+ Copyright (c) 2019-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a
8
+ copy of this software and associated documentation files (the "Software"),
9
+ to deal in the Software without restriction, including without limitation
10
+ the rights to use, copy, modify, merge, publish, distribute, sublicense,
11
+ and/or sell copies of the Software, and to permit persons to whom the
12
+ Software is furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23
+ DEALINGS IN THE SOFTWARE.
24
+ """
25
+
26
+ import cupy
27
+
28
+
29
+ _convolve1d2o_kernel = cupy.ElementwiseKernel(
30
+ 'raw T in1, raw T in2, int32 W, int32 H', 'T out',
31
+ """
32
+ T temp {};
33
+ for (int x = 0; x < W; x++) {
34
+ for (int y = 0; y < H; y++) {
35
+ temp += in1[i + W - x - 1] * in1[i + H - y - 1] * in2[H * x + y];
36
+ }
37
+ }
38
+ out = temp;
39
+ """,
40
+ "cupy_convolved2o",
41
+ )
42
+
43
+
44
+ def _convolve1d2o(in1, in2, mode):
45
+ assert mode == "valid"
46
+ out_dim = in1.shape[0] - max(in2.shape) + 1
47
+ dtype = cupy.result_type(in1, in2)
48
+ out = cupy.empty(out_dim, dtype=dtype)
49
+ _convolve1d2o_kernel(in1, in2, *in2.shape, out)
50
+ return out
51
+
52
+
53
+ def convolve1d2o(in1, in2, mode='valid', method='direct'):
54
+ """
55
+ Convolve a 1-dimensional arrays with a 2nd order filter.
56
+ This results in a second order convolution.
57
+
58
+ Convolve `in1` and `in2`, with the output size determined by the
59
+ `mode` argument.
60
+
61
+ Parameters
62
+ ----------
63
+ in1 : array_like
64
+ First input.
65
+ in2 : array_like
66
+ Second input. Should have the same number of dimensions as `in1`.
67
+ mode : str {'full', 'valid', 'same'}, optional
68
+ A string indicating the size of the output:
69
+
70
+ ``full``
71
+ The output is the full discrete linear convolution
72
+ of the inputs. (Default)
73
+ ``valid``
74
+ The output consists only of those elements that do not
75
+ rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
76
+ must be at least as large as the other in every dimension.
77
+ ``same``
78
+ The output is the same size as `in1`, centered
79
+ with respect to the 'full' output.
80
+ method : str {'auto', 'direct', 'fft'}, optional
81
+ A string indicating which method to use to calculate the convolution.
82
+
83
+ ``direct``
84
+ The convolution is determined directly from sums, the definition of
85
+ convolution.
86
+ ``fft``
87
+ The Fourier Transform is used to perform the convolution by calling
88
+ `fftconvolve`.
89
+ ``auto``
90
+ Automatically chooses direct or Fourier method based on an estimate
91
+ of which is faster (default).
92
+
93
+ Returns
94
+ -------
95
+ out : ndarray
96
+ A 1-dimensional array containing a subset of the discrete linear
97
+ convolution of `in1` with `in2`.
98
+
99
+ See Also
100
+ --------
101
+ convolve
102
+ convolve1d2o
103
+ convolve1d3o
104
+
105
+ Examples
106
+ --------
107
+ Convolution of a 2nd order filter on a 1d signal
108
+
109
+ >>> import cusignal as cs
110
+ >>> import numpy as np
111
+ >>> d = 50
112
+ >>> a = np.random.uniform(-1,1,(200))
113
+ >>> b = np.random.uniform(-1,1,(d,d))
114
+ >>> c = cs.convolve1d2o(a,b)
115
+
116
+ """
117
+
118
+ if in1.ndim != 1:
119
+ raise ValueError('in1 should have one dimension')
120
+ if in2.ndim != 2:
121
+ raise ValueError('in2 should have three dimension')
122
+
123
+ if mode in ["same", "full"]:
124
+ raise NotImplementedError("Mode == {} not implemented".format(mode))
125
+
126
+ if method == "direct":
127
+ return _convolve1d2o(in1, in2, mode)
128
+ else:
129
+ raise NotImplementedError("Only Direct method implemented")
130
+
131
+
132
+ _convolve1d3o_kernel = cupy.ElementwiseKernel(
133
+ 'raw T in1, raw T in2, int32 W, int32 H, int32 D', 'T out',
134
+ """
135
+ T temp {};
136
+ for (int x = 0; x < W; x++) {
137
+ for (int y = 0; y < H; y++) {
138
+ for (int z = 0; z < D; z++) {
139
+ temp += in1[i + W - x - 1] * in1[i + H - y - 1] *
140
+ in1[i + D - z - 1] * in2[(H * x + y) * D + z];
141
+ }
142
+ }
143
+ }
144
+ out = temp;
145
+ """,
146
+ "cupy_convolved3o",
147
+ )
148
+
149
+
150
+ def _convolve1d3o(in1, in2, mode):
151
+ assert mode == "valid"
152
+ out_dim = in1.shape[0] - max(in2.shape) + 1
153
+ dtype = cupy.result_type(in1, in2)
154
+ out = cupy.empty(out_dim, dtype=dtype)
155
+ _convolve1d3o_kernel(in1, in2, *in2.shape, out)
156
+ return out
157
+
158
+
159
+ def convolve1d3o(in1, in2, mode='valid', method='direct'):
160
+ """
161
+ Convolve a 1-dimensional array with a 3rd order filter.
162
+ This results in a third order convolution.
163
+
164
+ Convolve `in1` and `in2`, with the output size determined by the
165
+ `mode` argument.
166
+
167
+ Parameters
168
+ ----------
169
+ in1 : array_like
170
+ First input. Should have one dimension.
171
+ in2 : array_like
172
+ Second input. Should have three dimensions.
173
+ mode : str {'full', 'valid', 'same'}, optional
174
+ A string indicating the size of the output:
175
+
176
+ ``full``
177
+ The output is the full discrete linear convolution
178
+ of the inputs. (Default)
179
+ ``valid``
180
+ The output consists only of those elements that do not
181
+ rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
182
+ must be at least as large as the other in every dimension.
183
+ ``same``
184
+ The output is the same size as `in1`, centered
185
+ with respect to the 'full' output.
186
+ method : str {'auto', 'direct', 'fft'}, optional
187
+ A string indicating which method to use to calculate the convolution.
188
+
189
+ ``direct``
190
+ The convolution is determined directly from sums, the definition of
191
+ convolution.
192
+ ``fft``
193
+ The Fourier Transform is used to perform the convolution by calling
194
+ `fftconvolve`.
195
+ ``auto``
196
+ Automatically chooses direct or Fourier method based on an estimate
197
+ of which is faster (default).
198
+
199
+ Returns
200
+ -------
201
+ out : ndarray
202
+ A 1-dimensional array containing a subset of the discrete linear
203
+ convolution of `in1` with `in2`.
204
+
205
+ See Also
206
+ --------
207
+ convolve
208
+ convolve1d2o
209
+ convolve1d3o
210
+ """
211
+
212
+ if in1.ndim != 1:
213
+ raise ValueError('in1 should have one dimension')
214
+ if in2.ndim != 3:
215
+ raise ValueError('in2 should have three dimension')
216
+
217
+ if mode in ["same", "full"]:
218
+ raise NotImplementedError("Mode == {} not implemented".format(mode))
219
+
220
+ if method == "direct":
221
+ return _convolve1d3o(in1, in2, mode)
222
+ else:
223
+ raise NotImplementedError("Only Direct method implemented")
vllm/lib/python3.10/site-packages/cupyx/signal/_radartools/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from cupyx.signal._radartools._beamformers import mvdr # NOQA
2
+ from cupyx.signal._radartools._radartools import pulse_compression # NOQA
3
+ from cupyx.signal._radartools._radartools import pulse_doppler # NOQA
4
+ from cupyx.signal._radartools._radartools import cfar_alpha # NOQA
5
+ from cupyx.signal._radartools._radartools import ca_cfar # NOQA
vllm/lib/python3.10/site-packages/cupyx/signal/_radartools/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (417 Bytes). View file
 
vllm/lib/python3.10/site-packages/cupyx/signal/_radartools/__pycache__/_beamformers.cpython-310.pyc ADDED
Binary file (1.47 kB). View file
 
vllm/lib/python3.10/site-packages/cupyx/signal/_radartools/__pycache__/_radartools.cpython-310.pyc ADDED
Binary file (10.4 kB). View file
 
vllm/lib/python3.10/site-packages/cupyx/signal/_radartools/_beamformers.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2019-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a
4
+ # copy of this software and associated documentation files (the "Software"),
5
+ # to deal in the Software without restriction, including without limitation
6
+ # the rights to use, copy, modify, merge, publish, distribute, sublicense,
7
+ # and/or sell copies of the Software, and to permit persons to whom the
8
+ # Software is furnished to do so, subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in
11
+ # all copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16
+ # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18
+ # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19
+ # DEALINGS IN THE SOFTWARE.
20
+
21
+ import cupy as cp
22
+
23
+
24
+ def mvdr(x, sv, calc_cov=True):
25
+ """
26
+ Minimum variance distortionless response (MVDR) beamformer weights
27
+
28
+ Parameters
29
+ ----------
30
+ x : ndarray
31
+ Received signal or input covariance matrix, assume 2D array with
32
+ size [num_sensors, num_samples]
33
+
34
+ sv: ndarray
35
+ Steering vector, assume 1D array with size [num_sensors, 1]
36
+
37
+ calc_cov : bool
38
+ Determine whether to calculate covariance matrix. Simply put, calc_cov
39
+ defines whether x input is made of sensor/observation data or is
40
+ a precalculated covariance matrix
41
+
42
+ Note: Unlike MATLAB where input matrix x is of size MxN where N represents
43
+ the number of array elements, we assume row-major formatted data where each
44
+ row is assumed to be complex-valued data from a given sensor (i.e. NxM)
45
+ """
46
+ if x.shape[0] > x.shape[1]:
47
+ raise ValueError(
48
+ "Matrix has more sensors than samples. Consider \
49
+ transposing and remember cuSignal is row-major, unlike MATLAB"
50
+ )
51
+
52
+ if x.shape[0] != sv.shape[0]:
53
+ raise ValueError("Steering Vector and input data do not align")
54
+
55
+ if calc_cov:
56
+ x = cp.cov(x, dtype=x.dtype)
57
+
58
+ wB = cp.linalg.inv(x).dot(sv)
59
+ wA = sv.conj().dot(wB) # 1x1 scalar
60
+ return wB / wA
vllm/lib/python3.10/site-packages/cupyx/signal/_radartools/_radartools.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Some of the functions defined here were ported directly from CuSignal under
3
+ terms of the MIT license, under the following notice:
4
+
5
+ Copyright (c) 2019-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a
8
+ copy of this software and associated documentation files (the "Software"),
9
+ to deal in the Software without restriction, including without limitation
10
+ the rights to use, copy, modify, merge, publish, distribute, sublicense,
11
+ and/or sell copies of the Software, and to permit persons to whom the
12
+ Software is furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20
+ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23
+ DEALINGS IN THE SOFTWARE.
24
+ """
25
+
26
+ import cupy
27
+ from cupyx.scipy.signal import windows
28
+
29
+
30
+ def _pulse_preprocess(x, normalize, window):
31
+ if window is not None:
32
+ n = x.shape[-1]
33
+ if callable(window):
34
+ w = window(cupy.fft.fftfreq(n).astype(x.dtype))
35
+ elif isinstance(window, cupy.ndarray):
36
+ if window.shape != (n,):
37
+ raise ValueError("window must have the same length as data")
38
+ w = window
39
+ else:
40
+ w = windows.get_window(window, n, False).astype(x.dtype)
41
+ x = x * w
42
+
43
+ if normalize:
44
+ x = x / cupy.linalg.norm(x)
45
+
46
+ return x
47
+
48
+
49
+ def pulse_compression(x, template, normalize=False, window=None, nfft=None):
50
+ """
51
+ Pulse Compression is used to increase the range resolution and SNR
52
+ by performing matched filtering of the transmitted pulse (template)
53
+ with the received signal (x)
54
+
55
+ Parameters
56
+ ----------
57
+ x : ndarray
58
+ Received signal, assume 2D array with [num_pulses, sample_per_pulse]
59
+
60
+ template : ndarray
61
+ Transmitted signal, assume 1D array
62
+
63
+ normalize : bool
64
+ Normalize transmitted signal
65
+
66
+ window : array_like, callable, string, float, or tuple, optional
67
+ Specifies the window applied to the signal in the Fourier
68
+ domain.
69
+
70
+ nfft : int, size of FFT for pulse compression. Default is number of
71
+ samples per pulse
72
+
73
+ Returns
74
+ -------
75
+ compressedIQ : ndarray
76
+ Pulse compressed output
77
+ """
78
+ num_pulses, samples_per_pulse = x.shape
79
+ dtype = cupy.result_type(x, template)
80
+
81
+ if nfft is None:
82
+ nfft = samples_per_pulse
83
+
84
+ t = _pulse_preprocess(template, normalize, window)
85
+ fft_x = cupy.fft.fft(x, nfft)
86
+ fft_t = cupy.fft.fft(t, nfft)
87
+ out = cupy.fft.ifft(fft_x * fft_t.conj(), nfft)
88
+ if dtype.kind != 'c':
89
+ out = out.real
90
+ return out
91
+
92
+
93
+ def pulse_doppler(x, window=None, nfft=None):
94
+ """
95
+ Pulse doppler processing yields a range/doppler data matrix that represents
96
+ moving target data that's separated from clutter. An estimation of the
97
+ doppler shift can also be obtained from pulse doppler processing. FFT taken
98
+ across slow-time (pulse) dimension.
99
+
100
+ Parameters
101
+ ----------
102
+ x : ndarray
103
+ Received signal, assume 2D array with [num_pulses, sample_per_pulse]
104
+
105
+ window : array_like, callable, string, float, or tuple, optional
106
+ Specifies the window applied to the signal in the Fourier
107
+ domain.
108
+
109
+ nfft : int, size of FFT for pulse compression. Default is number of
110
+ samples per pulse
111
+
112
+ Returns
113
+ -------
114
+ pd_dataMatrix : ndarray
115
+ Pulse-doppler output (range/doppler matrix)
116
+ """
117
+ num_pulses, samples_per_pulse = x.shape
118
+
119
+ if nfft is None:
120
+ nfft = num_pulses
121
+
122
+ xT = _pulse_preprocess(x.T, False, window)
123
+ return cupy.fft.fft(xT, nfft).T
124
+
125
+
126
+ def cfar_alpha(pfa, N):
127
+ """
128
+ Computes the value of alpha corresponding to a given probability
129
+ of false alarm and number of reference cells N.
130
+
131
+ Parameters
132
+ ----------
133
+ pfa : float
134
+ Probability of false alarm.
135
+
136
+ N : int
137
+ Number of reference cells.
138
+
139
+ Returns
140
+ -------
141
+ alpha : float
142
+ Alpha value.
143
+ """
144
+ return N * (pfa ** (-1.0 / N) - 1)
145
+
146
+
147
+ def ca_cfar(array, guard_cells, reference_cells, pfa=1e-3):
148
+ """
149
+ Computes the cell-averaged constant false alarm rate (CA CFAR) detector
150
+ threshold and returns for a given array.
151
+ Parameters
152
+ ----------
153
+ array : ndarray
154
+ Array containing data to be processed.
155
+ guard_cells_x : int
156
+ One-sided guard cell count in the first dimension.
157
+ guard_cells_y : int
158
+ One-sided guard cell count in the second dimension.
159
+ reference_cells_x : int
160
+ one-sided reference cell count in the first dimension.
161
+ reference_cells_y : int
162
+ one-sided reference cell count in the second dimension.
163
+ pfa : float
164
+ Probability of false alarm.
165
+ Returns
166
+ -------
167
+ threshold : ndarray
168
+ CFAR threshold
169
+ return : ndarray
170
+ CFAR detections
171
+ """
172
+ shape = array.shape
173
+ if len(shape) > 2:
174
+ raise TypeError('Only 1D and 2D arrays are currently supported.')
175
+ mask = cupy.zeros(shape, dtype=cupy.float32)
176
+
177
+ if len(shape) == 1:
178
+ if len(array) <= 2 * guard_cells + 2 * reference_cells:
179
+ raise ValueError('Array too small for given parameters')
180
+ intermediate = cupy.cumsum(array, axis=0, dtype=cupy.float32)
181
+ N = 2 * reference_cells
182
+ alpha = cfar_alpha(pfa, N)
183
+ tpb = (32,)
184
+ bpg = ((len(array) - 2 * reference_cells - 2 * guard_cells +
185
+ tpb[0] - 1) // tpb[0],)
186
+ _ca_cfar_1d_kernel(bpg, tpb, (array, intermediate, mask,
187
+ len(array), N, cupy.float32(alpha),
188
+ guard_cells, reference_cells))
189
+ elif len(shape) == 2:
190
+ if len(guard_cells) != 2 or len(reference_cells) != 2:
191
+ raise TypeError('Guard and reference cells must be two '
192
+ 'dimensional.')
193
+ guard_cells_x, guard_cells_y = guard_cells
194
+ reference_cells_x, reference_cells_y = reference_cells
195
+ if shape[0] - 2 * guard_cells_x - 2 * reference_cells_x <= 0:
196
+ raise ValueError('Array first dimension too small for given '
197
+ 'parameters.')
198
+ if shape[1] - 2 * guard_cells_y - 2 * reference_cells_y <= 0:
199
+ raise ValueError('Array second dimension too small for given '
200
+ 'parameters.')
201
+ intermediate = cupy.cumsum(array, axis=0, dtype=cupy.float32)
202
+ intermediate = cupy.cumsum(intermediate, axis=1, dtype=cupy.float32)
203
+ N = 2 * reference_cells_x * (2 * reference_cells_y +
204
+ 2 * guard_cells_y + 1)
205
+ N += 2 * (2 * guard_cells_x + 1) * reference_cells_y
206
+ alpha = cfar_alpha(pfa, N)
207
+ tpb = (8, 8)
208
+ bpg_x = (shape[0] - 2 * (reference_cells_x + guard_cells_x) + tpb[0] -
209
+ 1) // tpb[0]
210
+ bpg_y = (shape[1] - 2 * (reference_cells_y + guard_cells_y) + tpb[1] -
211
+ 1) // tpb[1]
212
+ bpg = (bpg_x, bpg_y)
213
+ _ca_cfar_2d_kernel(bpg, tpb, (array, intermediate, mask,
214
+ shape[0], shape[1], N, cupy.float32(alpha),
215
+ guard_cells_x, guard_cells_y, reference_cells_x,
216
+ reference_cells_y))
217
+ return (mask, array - mask > 0)
218
+
219
+
220
+ _ca_cfar_2d_kernel = cupy.RawKernel(r'''
221
+ extern "C" __global__ void
222
+ _ca_cfar_2d_kernel(float * array, float * intermediate, float * mask,
223
+ int width, int height, int N, float alpha,
224
+ int guard_cells_x, int guard_cells_y,
225
+ int reference_cells_x, int reference_cells_y)
226
+ {
227
+ int i_init = threadIdx.x+blockIdx.x*blockDim.x;
228
+ int j_init = threadIdx.y+blockIdx.y*blockDim.y;
229
+ int i, j, x, y, offset;
230
+ int tro, tlo, blo, bro, tri, tli, bli, bri;
231
+ float outer_area, inner_area, T;
232
+ for (i=i_init; i<width-2*(guard_cells_x+reference_cells_x);
233
+ i += blockDim.x*gridDim.x){
234
+ for (j=j_init; j<height-2*(guard_cells_y+reference_cells_y);
235
+ j += blockDim.y*gridDim.y){
236
+ /* 'tri' is Top Right Inner (square), 'blo' is Bottom Left
237
+ * Outer (square), etc. These are the corners at which
238
+ * the intermediate array must be evaluated.
239
+ */
240
+ x = i+guard_cells_x+reference_cells_x;
241
+ y = j+guard_cells_y+reference_cells_y;
242
+ offset = x*height+y;
243
+ tro = (x+guard_cells_x+reference_cells_x)*height+y+
244
+ guard_cells_y+reference_cells_y;
245
+ tlo = (x-guard_cells_x-reference_cells_x-1)*height+y+
246
+ guard_cells_y+reference_cells_y;
247
+ blo = (x-guard_cells_x-reference_cells_x-1)*height+y-
248
+ guard_cells_y-reference_cells_y-1;
249
+ bro = (x+guard_cells_x+reference_cells_x)*height+y-
250
+ guard_cells_y-reference_cells_y-1;
251
+ tri = (x+guard_cells_x)*height+y+guard_cells_y;
252
+ tli = (x-guard_cells_x-1)*height+y+guard_cells_y;
253
+ bli = (x-guard_cells_x-1)*height+y-guard_cells_y-1;
254
+ bri = (x+guard_cells_x)*height+y-guard_cells_y-1;
255
+ /* It would be nice to eliminate the triple
256
+ * branching here, but it only occurs on the boundaries
257
+ * of the array (i==0 or j==0). So it shouldn't hurt
258
+ * overall performance much.
259
+ */
260
+ if (i>0 && j>0){
261
+ outer_area = intermediate[tro]-intermediate[tlo]-
262
+ intermediate[bro]+intermediate[blo];
263
+ } else if (i == 0 && j > 0){
264
+ outer_area = intermediate[tro]-intermediate[bro];
265
+ } else if (i > 0 && j == 0){
266
+ outer_area = intermediate[tro]-intermediate[tlo];
267
+ } else if (i == 0 && j == 0){
268
+ outer_area = intermediate[tro];
269
+ }
270
+ inner_area = intermediate[tri]-intermediate[tli]-
271
+ intermediate[bri]+intermediate[bli];
272
+ T = outer_area-inner_area;
273
+ T = alpha/N*T;
274
+ mask[offset] = T;
275
+ }
276
+ }
277
+ }
278
+ ''', '_ca_cfar_2d_kernel')
279
+
280
+
281
+ _ca_cfar_1d_kernel = cupy.RawKernel(r'''
282
+ extern "C" __global__ void
283
+ _ca_cfar_1d_kernel(float * array, float * intermediate, float * mask,
284
+ int width, int N, float alpha,
285
+ int guard_cells, int reference_cells)
286
+ {
287
+ int i_init = threadIdx.x+blockIdx.x*blockDim.x;
288
+ int i, x;
289
+ int br, bl, sr, sl;
290
+ float big_area, small_area, T;
291
+ for (i=i_init; i<width-2*(guard_cells+reference_cells);
292
+ i += blockDim.x*gridDim.x){
293
+ x = i+guard_cells+reference_cells;
294
+ br = x+guard_cells+reference_cells;
295
+ bl = x-guard_cells-reference_cells-1;
296
+ sr = x+guard_cells;
297
+ sl = x-guard_cells-1;
298
+ if (i>0){
299
+ big_area = intermediate[br]-intermediate[bl];
300
+ } else{
301
+ big_area = intermediate[br];
302
+ }
303
+ small_area = intermediate[sr]-intermediate[sl];
304
+ T = big_area-small_area;
305
+ T = alpha/N*T;
306
+ mask[x] = T;
307
+ }
308
+ }
309
+ ''', '_ca_cfar_1d_kernel')
vllm/lib/python3.10/site-packages/cupyx/time.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math as _math
2
+ import warnings as _warnings
3
+
4
+ import numpy as _numpy
5
+
6
+ import cupy as _cupy
7
+ from cupyx.profiler._time import _repeat, _PerfCaseResult # for tests # NOQA
8
+
9
+
10
+ # TODO(leofang): remove this function in CuPy v11
11
+ def repeat(
12
+ func, args=(), kwargs={}, n_repeat=10000, *,
13
+ name=None, n_warmup=10, max_duration=_math.inf, devices=None):
14
+ """ Timing utility for measuring time spent by both CPU and GPU.
15
+
16
+ This function is a very convenient helper for setting up a timing test. The
17
+ GPU time is properly recorded by synchronizing internal streams. As a
18
+ result, to time a multi-GPU function all participating devices must be
19
+ passed as the ``devices`` argument so that this helper knows which devices
20
+ to record. A simple example is given as follows:
21
+
22
+ .. code-block:: py
23
+
24
+ import cupy as cp
25
+ from cupyx.time import repeat
26
+
27
+ def f(a, b):
28
+ return 3 * cp.sin(-a) * b
29
+
30
+ a = 0.5 - cp.random.random((100,))
31
+ b = cp.random.random((100,))
32
+ print(repeat(f, (a, b), n_repeat=1000))
33
+
34
+
35
+ Args:
36
+ func (callable): a callable object to be timed.
37
+ args (tuple): positional arguments to be passed to the callable.
38
+ kwargs (dict): keyword arguments to be passed to the callable.
39
+ n_repeat (int): number of times the callable is called. Increasing
40
+ this value would improve the collected statistics at the cost
41
+ of longer test time.
42
+ name (str): the function name to be reported. If not given, the
43
+ callable's ``__name__`` attribute is used.
44
+ n_warmup (int): number of times the callable is called. The warm-up
45
+ runs are not timed.
46
+ max_duration (float): the maximum time (in seconds) that the entire
47
+ test can use. If the taken time is longer than this limit, the test
48
+ is stopped and the statistics collected up to the breakpoint is
49
+ reported.
50
+ devices (tuple): a tuple of device IDs (int) that will be timed during
51
+ the timing test. If not given, the current device is used.
52
+
53
+ Returns:
54
+ :class:`~cupyx.profiler._time._PerfCaseResult`:
55
+ an object collecting all test results.
56
+
57
+ .. warning::
58
+ This API is moved to :func:`cupyx.profiler.benchmark` since CuPy v10.
59
+ Access through ``cupyx.time`` is deprecated.
60
+ """
61
+
62
+ _warnings.warn(
63
+ 'cupyx.time.repeat has been moved to cupyx.profiler.benchmark since '
64
+ 'CuPy v10. Access through cupyx.time is deprecated and will be '
65
+ 'removed in the future.')
66
+ if name is None:
67
+ name = func.__name__
68
+
69
+ if devices is None:
70
+ devices = (_cupy.cuda.get_device_id(),)
71
+
72
+ if not callable(func):
73
+ raise ValueError('`func` should be a callable object.')
74
+ if not isinstance(args, tuple):
75
+ raise ValueError('`args` should be of tuple type.')
76
+ if not isinstance(kwargs, dict):
77
+ raise ValueError('`kwargs` should be of dict type.')
78
+ if not isinstance(n_repeat, int):
79
+ raise ValueError('`n_repeat` should be an integer.')
80
+ if not isinstance(name, str):
81
+ raise ValueError('`name` should be a string.')
82
+ if not isinstance(n_warmup, int):
83
+ raise ValueError('`n_warmup` should be an integer.')
84
+ if not _numpy.isreal(max_duration):
85
+ raise ValueError('`max_duration` should be given in seconds')
86
+ if not isinstance(devices, tuple):
87
+ raise ValueError('`devices` should be of tuple type')
88
+
89
+ return _repeat(
90
+ func, args, kwargs, n_repeat, name, n_warmup, max_duration, devices)
vllm/lib/python3.10/site-packages/fsspec/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.44 kB). View file
 
vllm/lib/python3.10/site-packages/fsspec/__pycache__/_version.cpython-310.pyc ADDED
Binary file (482 Bytes). View file
 
vllm/lib/python3.10/site-packages/fsspec/__pycache__/archive.cpython-310.pyc ADDED
Binary file (2.97 kB). View file
 
vllm/lib/python3.10/site-packages/fsspec/__pycache__/asyn.cpython-310.pyc ADDED
Binary file (29.3 kB). View file
 
vllm/lib/python3.10/site-packages/fsspec/__pycache__/caching.cpython-310.pyc ADDED
Binary file (23.8 kB). View file
 
vllm/lib/python3.10/site-packages/fsspec/__pycache__/callbacks.cpython-310.pyc ADDED
Binary file (10.9 kB). View file
 
vllm/lib/python3.10/site-packages/fsspec/__pycache__/compression.cpython-310.pyc ADDED
Binary file (5.08 kB). View file
 
vllm/lib/python3.10/site-packages/fsspec/__pycache__/config.cpython-310.pyc ADDED
Binary file (3.81 kB). View file
 
vllm/lib/python3.10/site-packages/fsspec/__pycache__/conftest.cpython-310.pyc ADDED
Binary file (1.55 kB). View file
 
vllm/lib/python3.10/site-packages/fsspec/__pycache__/core.cpython-310.pyc ADDED
Binary file (22.2 kB). View file
 
vllm/lib/python3.10/site-packages/fsspec/__pycache__/dircache.cpython-310.pyc ADDED
Binary file (3.4 kB). View file
 
vllm/lib/python3.10/site-packages/fsspec/__pycache__/fuse.cpython-310.pyc ADDED
Binary file (10.1 kB). View file
 
vllm/lib/python3.10/site-packages/fsspec/__pycache__/generic.cpython-310.pyc ADDED
Binary file (12.7 kB). View file
 
vllm/lib/python3.10/site-packages/fsspec/__pycache__/gui.cpython-310.pyc ADDED
Binary file (14.6 kB). View file