nvmath-python 0.5.0__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. nvmath/__init__.pxd +0 -0
  2. nvmath/__init__.py +37 -0
  3. nvmath/_internal/__init__.py +0 -0
  4. nvmath/_internal/layout.py +58 -0
  5. nvmath/_utils.py +363 -0
  6. nvmath/bindings/__init__.pxd +0 -0
  7. nvmath/bindings/__init__.py +44 -0
  8. nvmath/bindings/_internal/__init__.pxd +0 -0
  9. nvmath/bindings/_internal/__init__.py +0 -0
  10. nvmath/bindings/_internal/cublas.cp313-win_amd64.pyd +0 -0
  11. nvmath/bindings/_internal/cublas.pxd +518 -0
  12. nvmath/bindings/_internal/cublasLt.cp313-win_amd64.pyd +0 -0
  13. nvmath/bindings/_internal/cublasLt.pxd +54 -0
  14. nvmath/bindings/_internal/cudss.cp313-win_amd64.pyd +0 -0
  15. nvmath/bindings/_internal/cudss.pxd +44 -0
  16. nvmath/bindings/_internal/cufft.cp313-win_amd64.pyd +0 -0
  17. nvmath/bindings/_internal/cufft.pxd +69 -0
  18. nvmath/bindings/_internal/cufftMp.pxd +77 -0
  19. nvmath/bindings/_internal/curand.cp313-win_amd64.pyd +0 -0
  20. nvmath/bindings/_internal/curand.pxd +42 -0
  21. nvmath/bindings/_internal/cusolver.cp313-win_amd64.pyd +0 -0
  22. nvmath/bindings/_internal/cusolver.pxd +15 -0
  23. nvmath/bindings/_internal/cusolverDn.cp313-win_amd64.pyd +0 -0
  24. nvmath/bindings/_internal/cusolverDn.pxd +386 -0
  25. nvmath/bindings/_internal/cusparse.cp313-win_amd64.pyd +0 -0
  26. nvmath/bindings/_internal/cusparse.pxd +270 -0
  27. nvmath/bindings/_internal/mathdx.cp313-win_amd64.pyd +0 -0
  28. nvmath/bindings/_internal/mathdx.pxd +79 -0
  29. nvmath/bindings/_internal/nvshmem.pxd +29 -0
  30. nvmath/bindings/_internal/utils.cp313-win_amd64.pyd +0 -0
  31. nvmath/bindings/_internal/utils.pxd +186 -0
  32. nvmath/bindings/cublas.cp313-win_amd64.pyd +0 -0
  33. nvmath/bindings/cublas.pxd +545 -0
  34. nvmath/bindings/cublas.pyi +18 -0
  35. nvmath/bindings/cublasLt.cp313-win_amd64.pyd +0 -0
  36. nvmath/bindings/cublasLt.pxd +99 -0
  37. nvmath/bindings/cudss.cp313-win_amd64.pyd +0 -0
  38. nvmath/bindings/cudss.pxd +83 -0
  39. nvmath/bindings/cudss.pyi +249 -0
  40. nvmath/bindings/cufft.cp313-win_amd64.pyd +0 -0
  41. nvmath/bindings/cufft.pxd +114 -0
  42. nvmath/bindings/cufftMp.pxd +124 -0
  43. nvmath/bindings/curand.cp313-win_amd64.pyd +0 -0
  44. nvmath/bindings/curand.pxd +71 -0
  45. nvmath/bindings/cusolver.cp313-win_amd64.pyd +0 -0
  46. nvmath/bindings/cusolver.pxd +60 -0
  47. nvmath/bindings/cusolverDn.cp313-win_amd64.pyd +0 -0
  48. nvmath/bindings/cusolverDn.pxd +410 -0
  49. nvmath/bindings/cusparse.cp313-win_amd64.pyd +0 -0
  50. nvmath/bindings/cusparse.pxd +329 -0
  51. nvmath/bindings/cycublas.cp313-win_amd64.pyd +0 -0
  52. nvmath/bindings/cycublas.pxd +657 -0
  53. nvmath/bindings/cycublasLt.cp313-win_amd64.pyd +0 -0
  54. nvmath/bindings/cycublasLt.pxd +1010 -0
  55. nvmath/bindings/cycudss.cp313-win_amd64.pyd +0 -0
  56. nvmath/bindings/cycudss.pxd +191 -0
  57. nvmath/bindings/cycufft.cp313-win_amd64.pyd +0 -0
  58. nvmath/bindings/cycufft.pxd +320 -0
  59. nvmath/bindings/cycufftMp.pxd +333 -0
  60. nvmath/bindings/cycurand.cp313-win_amd64.pyd +0 -0
  61. nvmath/bindings/cycurand.pxd +146 -0
  62. nvmath/bindings/cycusolver.cp313-win_amd64.pyd +0 -0
  63. nvmath/bindings/cycusolver.pxd +143 -0
  64. nvmath/bindings/cycusolverDn.cp313-win_amd64.pyd +0 -0
  65. nvmath/bindings/cycusolverDn.pxd +414 -0
  66. nvmath/bindings/cycusparse.cp313-win_amd64.pyd +0 -0
  67. nvmath/bindings/cycusparse.pxd +476 -0
  68. nvmath/bindings/cymathdx.cp313-win_amd64.pyd +0 -0
  69. nvmath/bindings/cymathdx.pxd +363 -0
  70. nvmath/bindings/cynvshmem.pxd +126 -0
  71. nvmath/bindings/mathdx.cp313-win_amd64.pyd +0 -0
  72. nvmath/bindings/mathdx.pxd +131 -0
  73. nvmath/bindings/mathdx.pyi +686 -0
  74. nvmath/bindings/nvpl/__init__.pxd +0 -0
  75. nvmath/bindings/nvpl/__init__.py +11 -0
  76. nvmath/bindings/nvpl/_internal/__init__.pxd +0 -0
  77. nvmath/bindings/nvpl/_internal/__init__.py +0 -0
  78. nvmath/bindings/nvpl/_internal/fft.pxd +36 -0
  79. nvmath/bindings/nvpl/cyfft.pxd +87 -0
  80. nvmath/bindings/nvpl/fft.pxd +100 -0
  81. nvmath/bindings/nvshmem.pxd +54 -0
  82. nvmath/device/__init__.py +23 -0
  83. nvmath/device/_deprecated.py +33 -0
  84. nvmath/device/caching.py +51 -0
  85. nvmath/device/common.py +131 -0
  86. nvmath/device/common_backend.py +125 -0
  87. nvmath/device/common_cuda.py +156 -0
  88. nvmath/device/common_mathdx.py +97 -0
  89. nvmath/device/common_numba.py +159 -0
  90. nvmath/device/common_opaque_tensor.py +128 -0
  91. nvmath/device/cublasdx.py +1085 -0
  92. nvmath/device/cublasdx_backend.py +552 -0
  93. nvmath/device/cublasdx_numba.py +528 -0
  94. nvmath/device/cufftdx.py +551 -0
  95. nvmath/device/cufftdx_backend.py +194 -0
  96. nvmath/device/cufftdx_numba.py +123 -0
  97. nvmath/device/curand_kernel.py +9147 -0
  98. nvmath/device/nvrtc.py +95 -0
  99. nvmath/device/patch.py +35 -0
  100. nvmath/device/random.py +417 -0
  101. nvmath/device/random_helpers.py +23 -0
  102. nvmath/device/random_states.py +189 -0
  103. nvmath/device/types.py +11 -0
  104. nvmath/device/vector_types_numba.py +203 -0
  105. nvmath/distributed/__init__.py +117 -0
  106. nvmath/distributed/_internal/__init__.py +0 -0
  107. nvmath/distributed/_internal/nvshmem.py +243 -0
  108. nvmath/distributed/_internal/tensor_ifc_cupy.py +111 -0
  109. nvmath/distributed/_internal/tensor_ifc_numpy.py +53 -0
  110. nvmath/distributed/_internal/tensor_ifc_torch.py +108 -0
  111. nvmath/distributed/_internal/tensor_wrapper.py +59 -0
  112. nvmath/distributed/_utils.py +152 -0
  113. nvmath/distributed/fft/__init__.py +6 -0
  114. nvmath/distributed/fft/_configuration.py +86 -0
  115. nvmath/distributed/fft/fft.py +1737 -0
  116. nvmath/distributed/reshape/__init__.py +6 -0
  117. nvmath/distributed/reshape/_configuration.py +39 -0
  118. nvmath/distributed/reshape/reshape.py +1249 -0
  119. nvmath/fft/__init__.py +7 -0
  120. nvmath/fft/_configuration.py +208 -0
  121. nvmath/fft/_exec_utils.py +116 -0
  122. nvmath/fft/_helpers.py +260 -0
  123. nvmath/fft/fft.py +2346 -0
  124. nvmath/internal/__init__.py +5 -0
  125. nvmath/internal/enum_utils.py +142 -0
  126. nvmath/internal/formatters.py +87 -0
  127. nvmath/internal/mem_limit.py +51 -0
  128. nvmath/internal/package_ifc.py +119 -0
  129. nvmath/internal/package_ifc_cuda.py +43 -0
  130. nvmath/internal/package_ifc_cupy.py +49 -0
  131. nvmath/internal/package_ifc_torch.py +31 -0
  132. nvmath/internal/package_wrapper.py +14 -0
  133. nvmath/internal/tensor_ifc.py +143 -0
  134. nvmath/internal/tensor_ifc_cupy.py +185 -0
  135. nvmath/internal/tensor_ifc_numpy.py +157 -0
  136. nvmath/internal/tensor_ifc_torch.py +115 -0
  137. nvmath/internal/tensor_wrapper.py +160 -0
  138. nvmath/internal/typemaps.py +154 -0
  139. nvmath/internal/utils.py +634 -0
  140. nvmath/linalg/__init__.py +11 -0
  141. nvmath/linalg/_internal/__init__.py +3 -0
  142. nvmath/linalg/_internal/algo_cap_ifc.py +86 -0
  143. nvmath/linalg/_internal/algo_config_ifc.py +87 -0
  144. nvmath/linalg/_internal/enum_to_tuples.py +64 -0
  145. nvmath/linalg/_internal/epilog_protocol.py +738 -0
  146. nvmath/linalg/_internal/matmul_desc_ifc.py +72 -0
  147. nvmath/linalg/_internal/matmul_pref_ifc.py +65 -0
  148. nvmath/linalg/_internal/matrix_layout_ifc.py +59 -0
  149. nvmath/linalg/_internal/typemaps.py +135 -0
  150. nvmath/linalg/_internal/utils.py +96 -0
  151. nvmath/linalg/advanced/__init__.py +8 -0
  152. nvmath/linalg/advanced/_algorithmmod.py +142 -0
  153. nvmath/linalg/advanced/_configuration.py +320 -0
  154. nvmath/linalg/advanced/helpers/__init__.py +5 -0
  155. nvmath/linalg/advanced/helpers/matmul.py +173 -0
  156. nvmath/linalg/advanced/matmulmod.py +2855 -0
  157. nvmath/memory.py +266 -0
  158. nvmath/sparse/__init__.py +18 -0
  159. nvmath/sparse/_internal/__init__.py +21 -0
  160. nvmath/sparse/_internal/common_utils.py +81 -0
  161. nvmath/sparse/_internal/cudss_config_ifc.py +584 -0
  162. nvmath/sparse/_internal/cudss_data_ifc.py +291 -0
  163. nvmath/sparse/_internal/cudss_utils.py +398 -0
  164. nvmath/sparse/_internal/sparse_csr_ifc.py +154 -0
  165. nvmath/sparse/_internal/sparse_format_helpers.py +88 -0
  166. nvmath/sparse/_internal/sparse_tensor_ifc.py +80 -0
  167. nvmath/sparse/advanced/__init__.py +7 -0
  168. nvmath/sparse/advanced/_configuration.py +150 -0
  169. nvmath/sparse/advanced/direct_solver.py +1705 -0
  170. nvmath_python-0.5.0.dist-info/METADATA +122 -0
  171. nvmath_python-0.5.0.dist-info/RECORD +174 -0
  172. nvmath_python-0.5.0.dist-info/WHEEL +5 -0
  173. nvmath_python-0.5.0.dist-info/licenses/LICENSE +177 -0
  174. nvmath_python-0.5.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1705 @@
1
+ # Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. ALL RIGHTS RESERVED.
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+
6
+ __all__ = [
7
+ "direct_solver",
8
+ "DirectSolver",
9
+ "DirectSolverAlgType",
10
+ "DirectSolverFactorizationConfig",
11
+ "DirectSolverFactorizationInfo",
12
+ "DirectSolverPlanConfig",
13
+ "DirectSolverPlanInfo",
14
+ "DirectSolverSolutionConfig",
15
+ ]
16
+
17
+ from collections.abc import Sequence
18
+ import itertools
19
+ import math
20
+ import logging
21
+ import operator
22
+ import os
23
+ from typing import Any, TypeAlias
24
+
25
+ from nvmath.bindings import cudss
26
+
27
+ from nvmath.internal import formatters, utils
28
+ from nvmath.internal.package_wrapper import StreamHolder
29
+ from nvmath.internal import tensor_wrapper
30
+ from nvmath.sparse.advanced._configuration import DirectSolverOptions, ExecutionCUDA, ExecutionHybrid, HybridMemoryModeOptions
31
+ from nvmath.sparse._internal import common_utils as sp_utils
32
+ from nvmath.sparse._internal import cudss_config_ifc, cudss_data_ifc, cudss_utils
33
+
34
+
35
+ from nvmath.internal.typemaps import NAME_TO_DATA_TYPE
36
+
37
+
38
+ VALID_INDEX_TYPES = ("int32",)
39
+
40
+ VALID_DTYPES = ("float32", "float64", "complex64", "complex128")
41
+
42
+ # Qualified names for public export.
43
+ DirectSolverPlanConfig: TypeAlias = cudss_config_ifc.PlanConfig
44
+ DirectSolverFactorizationConfig: TypeAlias = cudss_config_ifc.FactorizationConfig
45
+ DirectSolverSolutionConfig: TypeAlias = cudss_config_ifc.SolutionConfig
46
+ DirectSolverPlanInfo: TypeAlias = cudss_data_ifc.PlanInfo
47
+ DirectSolverFactorizationInfo: TypeAlias = cudss_data_ifc.FactorizationInfo
48
+ DirectSolverAlgType: TypeAlias = cudss.AlgType
49
+
50
+
51
+ def get_threading_lib(library=None):
52
+ """
53
+ Return the name of the threading library, if defined using an environment variable and
54
+ the path is valid, or None.
55
+ """
56
+ if library is None:
57
+ library = os.getenv("CUDSS_THREADING_LIB")
58
+ if library is None or not os.path.isfile(library):
59
+ return
60
+ return library
61
+
62
+
63
+ def check_dense_tensor_layout(shape: Sequence[int], strides: Sequence[int], *, explicitly_batched=None):
64
+ """
65
+ Check that the dense vector or matrix (each sample matrix in a N-D tensor) is
66
+ in col-major format.
67
+ """
68
+
69
+ num_dimensions = len(shape)
70
+ assert explicitly_batched is not None and len(strides) == num_dimensions, "Internal Error."
71
+
72
+ # For explicitly batched matrices, each sample must be a matrix or vector.
73
+ if explicitly_batched and num_dimensions > 2:
74
+ return False
75
+
76
+ first = int(num_dimensions > 1)
77
+
78
+ # Only column-major matrices are currently supported.
79
+ is_col_major = strides[-1 - first] == 1
80
+
81
+ # Check that the LD doesn't lead to overlapping memory.
82
+ # For batched matrices, LD has to be equal to the first matrix dimension.
83
+ comparison_op_for_ld = operator.eq if num_dimensions > 2 else operator.ge
84
+
85
+ if num_dimensions > 1:
86
+ return is_col_major and comparison_op_for_ld(strides[-1], shape[-2])
87
+
88
+ return is_col_major
89
+
90
+
91
+ def check_rhs_sequence_layout(
92
+ shape: Sequence[Sequence[int]],
93
+ strides: Sequence[Sequence[int]],
94
+ ):
95
+ return all(check_dense_tensor_layout(s, d, explicitly_batched=True) for s, d in zip(shape, strides, strict=True))
96
+
97
+
98
+ # TODO: unify to tensor_wrapper.to() and the axis utilities below.
99
+ def copy_single_or_sequence(operands, device_id, stream_holder):
100
+ if isinstance(operands, Sequence):
101
+ return tuple(o.to(device_id, stream_holder) for o in operands)
102
+
103
+ return operands.to(device_id, stream_holder)
104
+
105
+
106
+ def axis_order_in_memory(shape, strides):
107
+ """
108
+ Compute the order in which the axes appear in memory.
109
+ """
110
+ # The shape is used to resolve cases like (1, 2, 1) : (2, 1, 1) in CuTe notation.
111
+ _, _, axis_order = zip(*sorted(zip(strides, shape, range(len(strides)), strict=True)), strict=True)
112
+
113
+ return axis_order
114
+
115
+
116
+ def calculate_strides(shape, axis_order):
117
+ """
118
+ Calculate the strides for the provided shape and axis order.
119
+ """
120
+ strides = [None] * len(shape)
121
+
122
+ stride = 1
123
+ for axis in axis_order:
124
+ strides[axis] = stride
125
+ stride *= shape[axis]
126
+
127
+ return strides
128
+
129
+
130
+ SHARED_DSS_DOCUMENTATION = utils.COMMON_SHARED_DOC_MAP.copy()
131
+ SHARED_DSS_DOCUMENTATION.update(
132
+ {
133
+ "a": """\
134
+ The sparse operand (or sequence of operands) representing the left-hand side (LHS) of the system of equations. The LHS
135
+ operand may be a (sequence of) :class:`scipy.sparse.csr_matrix`, :class:`scipy.sparse.csr_array`,
136
+ :class:`cupyx.scipy.sparse.csr_matrix`, or :py:func:`torch.sparse_csr_tensor`. That is, the LHS is a sparse matrix or
137
+ tensor in Compressed Sparse Row (CSR) format from one of the supported packages: SciPy, CuPy, PyTorch. Refer to the
138
+ :ref:`semantics <Semantics>` section for details.
139
+ """.replace("\n", " "),
140
+ #
141
+ "b": """\
142
+ The ndarray/tensor or (sequence of ndarray/tensors) representing the dense right-hand side (RHS) of the system of equations.
143
+ The RHS operand may be a (sequence of) :class:`numpy.ndarray`, :class:`cupy.ndarray`, and :class:`torch.Tensor`. Refer to the
144
+ :ref:`semantics <Semantics>` section for details.
145
+ """.replace("\n", " "),
146
+ #
147
+ "options": """\
148
+ Specify options for the direct sparse solver as a :class:`DirectSolverOptions` object. Alternatively, a `dict` containing
149
+ the parameters for the ``DirectSolverOptions`` constructor can also be provided. If not specified, the value will be set
150
+ to the default-constructed ``DirectSolverOptions`` object.""".replace("\n", " "),
151
+ #
152
+ "execution": """\
153
+ Specify execution space options for the direct solver as a :class:`ExecutionCUDA` or :class:`ExecutionHybrid` object.
154
+ Alternatively, a string ('cuda' or 'hybrid'), or a `dict` with the 'name' key set to 'cuda' or 'hybrid' and optional
155
+ parameters relevant to the given execution space. The default execution space is 'cuda' and the corresponding
156
+ :class:`ExecutionCUDA` object will be default-constructed.""".replace("\n", " "),
157
+ #
158
+ "result": """\
159
+ The result of the specified sparse direct solve, which has the same shape, remains on the same device, and belongs to the
160
+ same package as the RHS ``b``. If ``b`` is a sequence, the result ``x`` is also a sequence of ndarray/tensor, each of which
161
+ has the same shape as the corresponding tensor in ``b``.
162
+ """.replace("\n", " "),
163
+ #
164
+ "semantics": r"""\
165
+ The sparse direct solver solves :math:`a @ x = b` for ``x`` given the left-hand side (LHS) ``a`` and the right-hand side
166
+ (RHS) ``b``.
167
+
168
+ * In the simplest version with no batching, ``a`` is sparse (square) matrix of size ``n`` in Compressed Sparse Row (CSR)
169
+ format, and ``b`` is a dense vector or matrix. A matrix (2D ndarray or tensor) in the RHS is treated as multiple
170
+ column vectors corresponding to multiple solution vectors (i.e. ``x`` is the same shape as the RHS) to solve for.
171
+
172
+ .. important:: Currently, only column-major (Fortran) layout is supported for the RHS.
173
+
174
+ * Batching can be specified either **explicitly** or **implicitly**.
175
+
176
+ * An **explicitly-batched** LHS is provided as a Python sequence of sparse CSR matrices :math:`[a_0, a_1, ..., a_n]`.
177
+ Likewise an explicitly-batched RHS is provided as a sequence of vectors or matrices :math:`[b_0, b_1, ..., b_n]`.
178
+ The solver will solve all :math:`n` systems :math:`a_i @ x_i = b_i` for the solution sequence :math:`x_i`.
179
+ Each sample in explicit batching can be of a different size, with the only constraint being that a given
180
+ LHS size is consistent with that of its corresponding RHS.
181
+
182
+ * An **implicitly-batched** LHS is provided as a higher-dimensional :math:`N \geq 3D` sparse tensor in CSR format,
183
+ where the leading :math:`N - 2` dimensions are the batch dimensions, and the last two dimensions correspond to that
184
+ of the :math:`n \times n` sparse system. Currently, only PyTorch supports higher-dimensional sparse CSR tensors.
185
+ Likewise, an implicitly-batched RHS is provided as a :math:`N \geq 3D` dense ndarray/tensor, where the leading
186
+ :math:`N - 2` dimensions are the batch dimensions, and the last two dimensions correspond to the :math:`n \times 1`
187
+ vector or :math:`n \times m` matrix for each sample. The solver solves :math:`a_i @ x_i = b_i` for each sample
188
+ :math:`i` in the batch, and the solution ``x`` has the same shape as the RHS ``b``.
189
+
190
+ * Each sample :math:`a_i` and :math:`b_i` in the (explicitly- or implicitly-specified) batch are essentially
191
+ treated as, and subject to, the same rules as the case with no batching.
192
+
193
+ * The LHS and RHS batch specification is independent: for example, the LHS can be explicitly-batched while the
194
+ RHS is implicitly-batched (or vice-versa). The same batch specification can be used for both as well.
195
+
196
+ * The solution ``x`` always has the same form as the RHS ``b``. It is a sequence of matrices or vectors if
197
+ ``b`` is explicitly-batched, or a higher-dimensional ndarray/tensor if ``b`` is implicitly-batched.
198
+ """.strip(),
199
+ }
200
+ )
201
+
202
+
203
+ class InvalidDirectSolverState(Exception):
204
+ pass
205
+
206
+
207
+ @utils.docstring_decorator(SHARED_DSS_DOCUMENTATION, skip_missing=False)
208
+ class DirectSolver:
209
+ """
210
+ Create a stateful object that encapsulates the specified sparse direct solver
211
+ computations and required resources. This object ensures the validity of resources
212
+ during use and releases them when they are no longer needed to prevent misuse.
213
+
214
+ This object encompasses all functionalities of function-form API :func:`direct_solver`,
215
+ which is a convenience wrapper around it. The stateful object also allows for the
216
+ amortization of preparatory costs when the same solve operation is to be performed
217
+ with different left-hand side (LHS) and right-hand side (RHS) with the same problem
218
+ specification (see :meth:`reset_operands` for more details).
219
+
220
+ Using the stateful object typically involves the following steps:
221
+
222
+ 1. **Problem Specification**: Initialize the object with the defined operation and
223
+ options.
224
+ 2. **Preparation**: Use :meth:`plan` for reordering to minimize fill-in and
225
+ symbolic factorization for this specific direct sparse solver operation.
226
+ 3. **Execution**: Factorize and solve the system.
227
+ 4. **Resource Management**: Ensure all resources are released either by explicitly
228
+ calling :meth:`free` or by managing the stateful object within a context manager.
229
+
230
+ Detailed information on each step described above can be obtained by passing in a
231
+ :class:`logging.Logger` object to :class:`DirectSolverOptions` or by setting the
232
+ appropriate options in the root logger object, which is used by default:
233
+
234
+ >>> import logging
235
+ >>> logging.basicConfig(
236
+ ... level=logging.INFO,
237
+ ... format="%(asctime)s %(levelname)-8s %(message)s",
238
+ ... datefmt="%m-%d %H:%M:%S",
239
+ ... )
240
+
241
+ Args:
242
+ a: {a}
243
+
244
+ b: {b}
245
+
246
+ options: {options}
247
+
248
+ execution: {execution}
249
+
250
+ stream: {stream}
251
+
252
+ See Also:
253
+ :class:`DirectSolverPlanConfig`, :class:`DirectSolverFactorizationConfig`,
254
+ :class:`DirectSolverSolutionConfig`, :class:`DirectSolverPlanInfo`,
255
+ :class:`DirectSolverFactorizationInfo`, :class:`DirectSolverOptions`,
256
+ :class:`ExecutionCUDA`, :class:`ExecutionHybrid`, :meth:`plan`,
257
+ :meth:`reset_operands`, :meth:`factorize`, :meth:`solve`.
258
+
259
+ Examples:
260
+
261
+ >>> import numpy as np
262
+ >>> import scipy.sparse as sp
263
+ >>> import nvmath
264
+
265
+ Create a sparse float64 ndarray in CSR format on the CPU for the LHS.
266
+
267
+ >>> n = 16
268
+ >>> a = sp.random_array((n, n), density=0.5, format="csr", dtype="float64")
269
+
270
+ Ensure that the randomly-generated LHS is not singular.
271
+
272
+ >>> a += sp.diags_array([2.0] * n, format="csr", dtype="float64")
273
+
274
+ The RHS can be a vector or matrix. Here we create a random vector.
275
+
276
+ >>> b = np.random.rand(n).astype(dtype="float64")
277
+
278
+ We will define a sparse direct solver operation for solving the system a @ x = b
279
+ using the specialized sparse direct solver interface.
280
+
281
+ >>> solver = nvmath.sparse.advanced.DirectSolver(a, b)
282
+
283
+ Options can be provided above to control the behavior of the operation using the
284
+ `options` argument (see :class:`DirectSolverOptions`).
285
+
286
+ Next, plan the operation. The planning operation can be configured through
287
+ the :class:`DirectSolverPlanConfig` interface, which is accessed through
288
+ :attr:`plan_config`.
289
+
290
+ >>> plan_config = solver.plan_config
291
+
292
+ Here we set the reordering algorithm to choice 1.
293
+
294
+ >>> AlgType = nvmath.sparse.advanced.DirectSolverAlgType
295
+ >>> plan_config.reordering_algorithm = AlgType.ALG_1
296
+
297
+ Plan the operation, which reorders the system to minimize fill-in and performs the
298
+ symbolic factorization. Planning returns a :class:`DirectSolverPlanInfo` object,
299
+ whose attributes (such as row or column permutation) can be queried.
300
+
301
+ >>> plan_info = solver.plan()
302
+ >>> plan_info.col_permutation
303
+ array([ 0, 1, 8, 9, 2, 3, 4, 11, 15, 5, 10, 6, 12, 13, 7, 14],
304
+ dtype=int32)
305
+
306
+ The next step is to perform the numerical factorization of the system using
307
+ :meth:`factorize`. Similar to planning, the numerical factorization step can
308
+ also be configured if desired.
309
+
310
+ >>> fac_config = solver.factorization_config
311
+
312
+ Here we set the pivot epsilon value to ``1e-14``, instead of the default ``1e-13``.
313
+
314
+ >>> fac_config.pivot_eps = 1e-14
315
+
316
+ Factorize the system, which returns a :class:`DirectSolverFactorizationInfo` object,
317
+ whose attributes can be inspected. We print the Sylvester inertia here.
318
+
319
+ >>> fac_info = solver.factorize()
320
+ >>> fac_info.inertia
321
+ array([0, 0], dtype=int32)
322
+
323
+ Now solve the factorized system, and obtain the result `x` as a NumPy ndarray on
324
+ the CPU.
325
+
326
+ >>> x = solver.solve()
327
+
328
+ Finally, free the object's resources. To avoid having to explicitly making this
329
+ call, it's recommended to use the DirectSolver object as a context manager as
330
+ shown below, if possible.
331
+
332
+ >>> solver.free()
333
+
334
+ .. note:: All :class:`DirectSolver` methods execute on the package current stream
335
+ by default. Alternatively, the `stream` argument can be used to run a method on
336
+ a specified stream.
337
+
338
+ Let's now look at a batched solve with PyTorch operands on the GPU.
339
+
340
+ Create a 3D complex128 PyTorch sparse tensor on the GPU representing the LHS, along
341
+ with the corresponding RHS:
342
+
343
+ >>> import torch
344
+ >>> n = 8
345
+ >>> batch = 2
346
+ >>> device_id = 0
347
+
348
+ Prepare sample input data. Create a diagonally-dominant random CSR matrix.
349
+
350
+ >>> a = torch.rand(n, n, dtype=torch.complex128) + torch.diag(torch.tensor([2.0] * n))
351
+ >>> a = torch.stack([a] * batch, dim=0)
352
+ >>> a = a.to_sparse_csr()
353
+
354
+ .. important:: PyTorch uses int64 for index buffers, whereas cuDSS currently
355
+ requires int32. So we'll have to convert the indices.
356
+
357
+ >>> a = torch.sparse_csr_tensor(
358
+ ... a.crow_indices().to(dtype=torch.int32),
359
+ ... a.col_indices().to(dtype=torch.int32),
360
+ ... a.values(),
361
+ ... size=a.size(),
362
+ ... device=device_id,
363
+ ... )
364
+
365
+ Create the RHS, which can be a matrix or vector in column-major layout.
366
+
367
+ >>> b = torch.ones(batch, 3, n, dtype=torch.complex128, device=device_id)
368
+ >>> b = b.permute(0, 2, 1)
369
+
370
+ Create a :class:`DirectSolver` object encapsulating the problem specification
371
+ described earlier and use it as a context manager.
372
+
373
+ >>> with nvmath.sparse.advanced.DirectSolver(a, b) as solver:
374
+ ... plan_info = solver.plan()
375
+ ...
376
+ ... # Factorize the system.
377
+ ... fac_info = solver.factorize()
378
+ ...
379
+ ... # Solve the factorized system.
380
+ ... x1 = solver.solve()
381
+ ...
382
+ ... # Update the RHS b in-place (see reset_operands() for an alternative).
383
+ ... b[...] = torch.rand(*b.shape, dtype=torch.complex128, device=device_id)
384
+ ...
385
+ ... # Solve again to get the new result.
386
+ ... x2 = solver.solve()
387
+
388
+ All the resources used by the object are released at the end of the block.
389
+
390
+ Batching can be implicitly-specified as shown above, or explicitly-specified as
391
+ a sequence for both the LHS and the RHS. This, as well as other options and
392
+ usage patterns, are illustrated in the examples found in the
393
+ `nvmath/examples/sparse/advanced/direct_solver
394
+ <https://github.com/NVIDIA/nvmath-python/tree/main/examples/sparse/advanced/direct_solver>`_
395
+ directory.
396
+ """ # noqa: W505
397
+
398
+ def __init__(
399
+ self,
400
+ a,
401
+ b,
402
+ *,
403
+ options: DirectSolverOptions | None = None,
404
+ execution: ExecutionCUDA | ExecutionHybrid | None = None,
405
+ stream: utils.AnyStream | int | None = None,
406
+ ):
407
+ # Process options.
408
+ self.options: Any = utils.check_or_create_options(DirectSolverOptions, options, "sparse direct solver options")
409
+
410
+ # Process execution options. The default execution space is CUDA.
411
+ self.execution_options = utils.check_or_create_one_of_options(
412
+ (ExecutionCUDA, ExecutionHybrid), execution, "execution options", default_name="cuda"
413
+ )
414
+ if self.execution_options.name == "cuda":
415
+ self.execution_options.hybrid_memory_mode_options = utils.check_or_create_options(
416
+ HybridMemoryModeOptions,
417
+ self.execution_options.hybrid_memory_mode_options,
418
+ "hybrid memory mode options",
419
+ )
420
+
421
+ self.logger = self.options.logger if self.options.logger is not None else logging.getLogger()
422
+ self.logger.info("= SPECIFICATION PHASE =")
423
+
424
+ # Wrap the LHS.
425
+ try:
426
+ self.a = sp_utils.wrap_sparse_operands(a)
427
+ except Exception as e:
428
+ raise TypeError(
429
+ """The LHS must be an N-D sparse CSR array/tensor or a sequence of 2D sparse CSR array/tensor from one
430
+ of the supported packages: CuPy, PyTorch, or SciPy."""
431
+ ) from e
432
+
433
+ # The LHS can be implicitly (N-D CSR tensor) or explicitly batched (provided as a
434
+ # sequence of CSR matrices).
435
+ self.implicitly_batched_lhs = False
436
+ self.explicitly_batched_lhs = isinstance(self.a, Sequence)
437
+ if not self.explicitly_batched_lhs:
438
+ self.implicitly_batched_lhs = self.a.num_dimensions > 2
439
+
440
+ # For explicitly batched LHS, check that all operands are matrices.
441
+ if self.explicitly_batched_lhs and any(a.num_dimensions > 2 for a in self.a):
442
+ raise TypeError(
443
+ f"""Every operator in the batched LHS provided as a sequence (explicit batching) must be a CSR matrix.
444
+ The specified LHS sequence = {a}."""
445
+ )
446
+
447
+ # The determination of a batched solve is purely based on the LHS. The RHS for each
448
+ # sample in the batch for explicit batching can be a vector or matrix, with the
449
+ # latter being considered multiple-RHS vectors as opposed to a batch. An
450
+ # implicitly-batched RHS is always 3D or higher dimension (implicitly-batched
451
+ # vectors are batched matrices with the last dimension of unit extent).
452
+ self.batched = self.explicitly_batched_lhs or self.implicitly_batched_lhs
453
+
454
+ # The LHS batch shape should be empty for explicit batching.
455
+ self.lhs_batch_shape: Any = None if self.explicitly_batched_lhs else tuple(self.a.shape[:-2])
456
+
457
+ # Set the LHS package.
458
+ if self.explicitly_batched_lhs:
459
+ # The package is the same for explicitly batched LHS since we've have
460
+ # successfully wrapped them.
461
+ self.lhs_package = utils.infer_object_package(self.a[0].tensor)
462
+ else: # Single or implicitly-batched LHS.
463
+ self.lhs_package = utils.infer_object_package(self.a.tensor)
464
+
465
+ # Determine the batch count and batch indices.
466
+ self.batch_count = 0
467
+ self.batch_indices = None # Needed only for implicit batching.
468
+ if self.explicitly_batched_lhs:
469
+ self.batch_count = len(self.a)
470
+ elif self.implicitly_batched_lhs:
471
+ self.batch_count = math.prod(self.lhs_batch_shape)
472
+ # Create the sequence of batch coordinates to use for creating batched CSR
473
+ # matrix type.
474
+ self.batch_indices = tuple(itertools.product(*list(map(range, self.lhs_batch_shape)))) # type: ignore
475
+
476
+ self.logger.info(f"The LHS package is {self.lhs_package}.")
477
+ if self.explicitly_batched_lhs:
478
+ self.logger.info(f"The LHS is explicitly batched, with a batch count of {self.batch_count}.")
479
+ elif self.implicitly_batched_lhs:
480
+ self.logger.info(
481
+ f"The LHS is implicitly batched with shape = {self.a.shape}, dtype = {self.a.dtype}, \
482
+ and index type = {self.a.index_type}."
483
+ )
484
+ self.logger.info(f"The LHS batch shape is {self.lhs_batch_shape}, with a batch count of {self.batch_count}.")
485
+ self.logger.debug(f"The batch indices (generated from the LHS) are: {self.batch_indices}.")
486
+
487
+ # Wrap the RHS. It can be a N-D tensor or a sequence of matrices or vectors.
488
+ self.rhs_batch_shape = ()
489
+ self.implicitly_batched_rhs = self.explicitly_batched_rhs = False
490
+ if isinstance(b, Sequence):
491
+ self.explicitly_batched_rhs = True
492
+ self.b: Any = tensor_wrapper.wrap_operands(b)
493
+ # For explicitly batched RHS, check that all operands are vectors or matrices.
494
+ if any(len(r.shape) > 2 for r in self.b):
495
+ raise TypeError(
496
+ f"""Every RHS object in the batched RHS provided as a sequence (explicit batching) must be a dense matrix
497
+ or vector. The specified RHS sequence = {b}."""
498
+ )
499
+ rhs_batch_count = len(self.b)
500
+ else:
501
+ self.b = tensor_wrapper.wrap_operand(b) # type:ignore
502
+ self.implicitly_batched_rhs = len(self.b.shape) > 2
503
+ self.rhs_batch_shape = tuple(self.b.shape[:-2]) # type: ignore
504
+ if self.implicitly_batched_lhs and self.lhs_batch_shape != self.rhs_batch_shape:
505
+ raise TypeError(
506
+ f"The batch shapes for the LHS {self.lhs_batch_shape} and RHS {self.rhs_batch_shape} must match."
507
+ )
508
+ rhs_batch_count = math.prod(self.rhs_batch_shape) if self.rhs_batch_shape else 0
509
+ if self.batch_indices is None:
510
+ # Create the sequence of batch coordinates to use for creating batched dense
511
+ # matrix type.
512
+ self.batch_indices = tuple(itertools.product(*list(map(range, self.rhs_batch_shape))))
513
+ self.logger.debug(f"The batch indices (generated from the RHS) are: {self.batch_indices}.")
514
+
515
+ # The LHS can be implicitly or explicitly batched, independent from how the RHS is
516
+ # batched. So we need to check that the batch counts match.
517
+ if rhs_batch_count != self.batch_count:
518
+ raise TypeError(f"The batch count for the LHS {self.batch_count} and RHS {rhs_batch_count} must match.")
519
+
520
+ # Set the RHS package.
521
+ if self.explicitly_batched_rhs:
522
+ # The package is the same for explicitly batched RHS since we've have
523
+ # successfully wrapped them.
524
+ self.rhs_package = utils.infer_object_package(self.b[0].tensor)
525
+ else: # Single or implicitly-batched RHS
526
+ self.rhs_package = utils.infer_object_package(self.b.tensor)
527
+
528
+ self.logger.info(f"The RHS package is {self.rhs_package}.")
529
+ if self.explicitly_batched_rhs:
530
+ self.logger.info(f"The RHS is explicitly batched, with a batch count of {rhs_batch_count}.")
531
+ elif self.implicitly_batched_rhs:
532
+ self.logger.info(f"The RHS is implicitly batched with shape = {self.b.shape} and dtype = {self.b.dtype}")
533
+ self.logger.info(f"The RHS batch shape is {self.rhs_batch_shape}, with a batch count of {rhs_batch_count}.")
534
+
535
+ # Note that while the LHS and RHS packages can be different they must be compatible
536
+ # (such as scipy-numpy, cupyx-cupy).
537
+ if (self.lhs_package, self.rhs_package) not in cudss_utils.COMPATIBLE_LHS_RHS_PACKAGES:
538
+ raise TypeError(
539
+ f"""The LHS package {self.lhs_package} and RHS package {self.rhs_package} are not part of the
540
+ compatible choices: {cudss_utils.COMPATIBLE_LHS_RHS_PACKAGES}."""
541
+ )
542
+
543
+ # Get key LHS attributes and perform more basic checks.
544
+ if self.explicitly_batched_lhs:
545
+ # For sequence, the get_[attribute]() functions check for consistency within
546
+ # the sequence.
547
+ self.device_id = utils.get_operands_device_id(self.a)
548
+ self.value_type = utils.get_operands_dtype(self.a)
549
+ self.index_type = sp_utils.get_operands_index_type(self.a)
550
+ self.lhs_shape = shapes = tuple(o.shape for o in self.a)
551
+ if any(len(s) != 2 or s[0] != s[1] for s in shapes):
552
+ raise TypeError("Each object in an explicitly-batched LHS must be a CSR matrix of shape (N, N).")
553
+ self._N = tuple(s[0] for s in shapes)
554
+ self.lhs_nnz = tuple(o.values.size for o in self.a)
555
+ else: # Single or implicitly-batched LHS
556
+ self.device_id = self.a.device_id
557
+ self.value_type = self.a.dtype
558
+ self.index_type = self.a.index_type
559
+ message = f"The LHS {self.a.tensor} must be a CSR matrix of shape (N, N) or CSR tensor with shape (..., N, N)."
560
+ if self.a.num_dimensions < 2:
561
+ raise TypeError(message)
562
+ n, m = self.a.shape[-2:]
563
+ if n != m:
564
+ raise TypeError(message)
565
+ self.lhs_shape = self.a.shape
566
+ self._N = n
567
+ self.lhs_nnz = self.a.values.size
568
+
569
+ # Note that torch by default uses int64 which is not supported. SciPy and CuPy adapt
570
+ # the index type based on the dimension.
571
+ if self.index_type not in VALID_INDEX_TYPES:
572
+ raise TypeError(
573
+ f"The index type {self.index_type} is not supported. The supported index types are {VALID_INDEX_TYPES}."
574
+ )
575
+
576
+ if self.value_type not in VALID_DTYPES:
577
+ raise TypeError(
578
+ f"The dtype (value type) {self.value_type} is not supported. The supported dtypes are {VALID_DTYPES}."
579
+ )
580
+
581
+ # Get key RHS attributes and perform more basic checks.
582
+ if self.explicitly_batched_rhs:
583
+ # For a sequence, the get_attribute functions check for consistency within
584
+ # the sequence.
585
+ rhs_device_id = utils.get_operands_device_id(self.b)
586
+ rhs_value_type = utils.get_operands_dtype(self.b)
587
+ self.rhs_shape = tuple(o.shape for o in self.b)
588
+ self.rhs_strides = tuple(o.strides for o in self.b)
589
+ if not check_rhs_sequence_layout(self.rhs_shape, self.rhs_strides):
590
+ raise TypeError(
591
+ f"Each object in an explicitly-batched RHS {[o.tensor for o in self.b]} must be a dense matrix or vector \
592
+ with compact col-major layout."
593
+ )
594
+ # For explicitly-batched RHS, the matrix or vector is compact so we can use
595
+ # the RHS strides for the result.
596
+ self.result_strides = self.rhs_strides
597
+ # Capture the RHS solution extent for compatibility check with the LHS.
598
+ self.rhs_n = tuple(s[0] for s in self.rhs_shape) # sample is not batched.
599
+ else: # Single or implicitly-batched RHS
600
+ rhs_device_id = self.b.device_id
601
+ rhs_value_type = self.b.dtype
602
+ self.rhs_shape = self.b.shape
603
+ self.rhs_strides = self.b.strides
604
+ if not check_dense_tensor_layout(self.rhs_shape, self.rhs_strides, explicitly_batched=False):
605
+ raise TypeError(
606
+ f"The RHS {self.b.tensor} must be a matrix or vector with col-major layout, and for implicitly-batched \
607
+ RHS (N-D >= 3), each matrix sample must have col-major layout (the second dimension from the end must have unit stride."
608
+ )
609
+ # For single or implicitly-batched RHS, the matrix may not be compact so we use
610
+ # the axis ordering to determine the strides.
611
+ axis_order = axis_order_in_memory(self.rhs_shape, self.rhs_strides)
612
+ self.result_strides = calculate_strides(self.rhs_shape, axis_order)
613
+ self.rhs_n = self.rhs_shape[-2] if len(self.rhs_shape) > 1 else self.rhs_shape[-1]
614
+
615
+ # Consistency within LHS and RHS sequence has been checked at this point.
616
+ # Now check that the extents match between a and b in Ax = b.
617
+ message = "The extent N corresponding to the number of equations is not consistent between the LHS and RHS."
618
+ if self.explicitly_batched_lhs:
619
+ if self.explicitly_batched_rhs:
620
+ if not all(x == y for (x, y) in zip(self._N, self.rhs_n, strict=True)):
621
+ raise TypeError(message)
622
+ elif self.implicitly_batched_rhs:
623
+ if not all(x == self.rhs_n for x in self._N):
624
+ raise TypeError(message)
625
+ else:
626
+ raise TypeError("The RHS is not batched, but the LHS is.")
627
+ elif self.implicitly_batched_lhs:
628
+ if self.explicitly_batched_rhs:
629
+ if not all(x == self._N for x in self.rhs_n):
630
+ raise TypeError(message)
631
+ elif self.implicitly_batched_rhs:
632
+ if self.rhs_n != self._N:
633
+ raise TypeError(message)
634
+ else:
635
+ raise TypeError("The RHS is not batched, but the LHS is.")
636
+ else:
637
+ if self.rhs_n != self._N:
638
+ raise TypeError(message)
639
+
640
+ if self.device_id != rhs_device_id:
641
+ raise TypeError(f"The LHS device ID {self.device_id} does not match the RHS device ID {rhs_device_id}.")
642
+
643
+ if self.value_type != rhs_value_type:
644
+ raise TypeError(f"The LHS dtype {self.value_type} does not match the RHS dtype {rhs_value_type}.")
645
+
646
+ # The RHS index type is currently always set to int32.
647
+
648
+ # The value types must currently be the same between a, x, and b.
649
+ self.result_data_type = self.value_type
650
+
651
+ self.logger.info(f"The device_id={self.device_id}, dtype = {self.value_type}, index type = {self.index_type}.")
652
+ self.logger.info(f"The number of equations = {self._N}.")
653
+ self.logger.debug(f"The LHS shape = {self.lhs_shape}.")
654
+ self.logger.debug(f"The RHS shape = {self.lhs_shape}, strides = {self.rhs_strides}.")
655
+
656
+ # Currently the value and index types must match between the LHS and RHS.
657
+ self.cuda_value_type = NAME_TO_DATA_TYPE[self.value_type]
658
+ self.cuda_index_type = NAME_TO_DATA_TYPE[self.index_type]
659
+
660
+ # For batched LHS and RHS check package, device_id, dtype, index_type is the same.
661
+ # Check consistency between LHS and RHS (same attributes, numpy -> scipy)
662
+ # Check that the size (_N) of each sample is consistent between LHS and RHS.
663
+
664
+ # Set the memory space "cuda" or "cpu".
665
+ self.memory_space = self.a[0].device if self.explicitly_batched_lhs else self.a.device
666
+
667
+ # Set the execution space "cuda" or "hybrid".
668
+ self.execution_space = self.execution_options.name
669
+
670
+ # Note #1: The device ID of the result is the same as that of the operands for
671
+ # hybrid execution since we don't copy them. Capture the original device here
672
+ # before it's potentially changed below. Also see note #3.
673
+ self.result_device_id = self.device_id
674
+
675
+ # Track potential issue with copying NumPy ndarray to GPU.
676
+ # TODO: This should be fixed when we use cuda.core for copying across memspace.
677
+ rhs_layout_flag = self.rhs_package == "numpy" and len(self.rhs_shape) > 2 and self.implicitly_batched_rhs
678
+
679
+ if self.device_id == "cpu":
680
+ # Note #2: We always set the RHS package to one that supports GPU execution,
681
+ # irrespective of whether it's hybrid or CUDA execution since we need the
682
+ # current stream.
683
+ if self.rhs_package == "numpy":
684
+ self.rhs_package = "cupy"
685
+ # TODO: remove this call after cupy is dropped.
686
+ tensor_wrapper.maybe_register_package("cupy")
687
+ # For CPU operands, set the device ID based on the execution options.
688
+ self.device_id = self.execution_options.device_id
689
+ self.logger.info(
690
+ f"The operands' memory space is {self.memory_space}, and the execution space is on device {self.device_id}."
691
+ )
692
+
693
+ self.copy_across_memspace = False
694
+ if self.execution_space == "hybrid":
695
+ # No need to copy CPU operands.
696
+ if self.batched:
697
+ raise TypeError(f"Batching is not supported for hybrid execution: {self.execution_options}.")
698
+
699
+ # For non-batched b, matrix (multiple-RHS) is not supported for CPU memory
700
+ # space (seems to be ignored for CUDA as well).
701
+ if len(self.b.shape) > 1:
702
+ raise TypeError(f"Matrix RHS (multiple RHS) is not supported for hybrid execution: {self.execution_options}.")
703
+ else: # execute in the CUDA space.
704
+ # The operands must be on the GPU even for *hybrid memory* mode for CUDA
705
+ # execution.
706
+ self.copy_across_memspace = self.memory_space != "cuda"
707
+ # Note #3: For CUDA execution, the result's device ID should be that of the
708
+ # execution device (self.device_id), where the operands also reside (may or
709
+ # may not be copied, depending on their original memspace). Also see note #1.
710
+ self.result_device_id = self.device_id
711
+
712
+ # Flag whether to copy CPU operands to GPU or not, based on execution option.
713
+ # - if hybrid execution, check not batched and nrhs==1. Accept CPU or GPU
714
+ # operands.
715
+ # - if hybrid memory and CUDA execution, need to copy to GPU.
716
+
717
+ # Create the stream holder.
718
+ stream_holder = utils.get_or_create_stream(self.device_id, stream, self.rhs_package)
719
+ self.logger.info(f"The specified stream for the DirectSolver ctor is {stream_holder.obj}.")
720
+
721
+ # cupy.asarray() doesn't preserve layout for > 2D arrays when copying from CPU
722
+ # to GPU.
723
+ if self.copy_across_memspace and rhs_layout_flag:
724
+ raise TypeError(
725
+ f"Implicit RHS batching for NumPy ndarrays is currently not supported with CUDA execution \
726
+ since the layout cannot be preserved when copying to the GPU (shape = {self.rhs_shape}, strides = {self.rhs_strides})."
727
+ )
728
+
729
+ # Copy operands to device if needed.
730
+ if self.copy_across_memspace:
731
+ self.a = copy_single_or_sequence(self.a, self.device_id, stream_holder)
732
+ self.b = copy_single_or_sequence(self.b, self.device_id, stream_holder)
733
+
734
+ # Create (batched or not, CSR or dense) matrix pointers for the LHS and RHS.
735
+ self.resources_a, self.a_ptr = cudss_utils.create_cudss_csr_wrapper(
736
+ self.cuda_index_type,
737
+ self.cuda_value_type,
738
+ self.index_type,
739
+ self.options.sparse_system_type,
740
+ self.options.sparse_system_view,
741
+ self.batch_indices,
742
+ self.a,
743
+ stream_holder,
744
+ )
745
+ self.resources_b, self.b_ptr = cudss_utils.create_cudss_dense_wrapper(
746
+ self.cuda_index_type, self.cuda_value_type, self.index_type, self.batch_indices, self.b, stream_holder
747
+ )
748
+
749
+ # Use `b` for creating the (potentially explicitly or implicitly batched) solution
750
+ # matrix or vector. The pointers will be updated later in execute.
751
+ self.resources_x, self.x_ptr = cudss_utils.create_cudss_dense_wrapper(
752
+ self.cuda_index_type, self.cuda_value_type, self.index_type, self.batch_indices, self.b, stream_holder
753
+ )
754
+
755
+ # Create or set handle, and create config and data pointers.
756
+ with utils.device_ctx(self.device_id):
757
+ if self.options.handle is not None:
758
+ self.own_handle = False
759
+ self.handle = self.options.handle
760
+ self.logger.info(f"The library handle has been set to the specified value: {self.handle}.")
761
+ else:
762
+ self.own_handle = True
763
+ self.handle = cudss.create()
764
+ self.logger.info(f"The library handle has been created: {self.handle}.")
765
+
766
+ self.config_ptr = cudss.config_create()
767
+ self.data_ptr = cudss.data_create(self.handle)
768
+
769
+ # Create the config interfaces for the various phases.
770
+ self._plan_config = cudss_config_ifc.PlanConfig(self)
771
+ self._factorization_config = cudss_config_ifc.FactorizationConfig(self)
772
+ self._solution_config = cudss_config_ifc.SolutionConfig(self)
773
+
774
+ # Create the data interfaces for the various phases.
775
+ self._plan_info = cudss_data_ifc.PlanInfo(self)
776
+ self._factorization_info = cudss_data_ifc.FactorizationInfo(self)
777
+
778
+ # Set the threading layer, if available.
779
+ threading_lib = get_threading_lib(self.options.multithreading_lib)
780
+ if threading_lib is not None:
781
+ cudss.set_threading_layer(self.handle, threading_lib)
782
+ else:
783
+ self.logger.warning(
784
+ "No multithreading interface library was specified using the \
785
+ DirectSolverOptions. The performance of CPU operations like planning will \
786
+ be significantly lower than if you provide a multithreading library."
787
+ )
788
+
789
+ # This doesn't guarantee that the library is usable, just that it is present.
790
+ self.multithreading = threading_lib is not None
791
+
792
+ # Set private attributes based on the options.
793
+ self._internal_config = cudss_config_ifc.InternalConfig(self)
794
+
795
+ # Set hybrid execution options. We have already checked that for batching and
796
+ # matrix RHS, which are not currently supported.
797
+ if self.execution_space == "hybrid":
798
+ self._internal_config.hybrid_execute_mode = 1
799
+ num_threads = self.execution_options.num_threads
800
+ if num_threads is not None:
801
+ if num_threads > 1 and threading_lib is None:
802
+ raise ValueError(f"""The threading library must be specified if the number of threads is more
803
+ than 1 (num_threads = {num_threads}.""")
804
+ self._internal_config.host_nthreads = num_threads
805
+
806
+ # Set CUDA execution options (including hybrid memory mode).
807
+ if self.execution_space == "cuda":
808
+ hmo = self.execution_options.hybrid_memory_mode_options
809
+ self._internal_config.hybrid_mode = hmo.hybrid_memory_mode
810
+ # Set device memory limit for hybrid memory.
811
+ if hmo.hybrid_device_memory_limit is not None:
812
+ memory_limit = utils.get_memory_limit_from_device_id(hmo.hybrid_device_memory_limit, self.device_id)
813
+ self.logger.info(f"The hybrid memory limit is {formatters.MemoryStr(memory_limit)}.")
814
+ self._internal_config.hybrid_device_memory_limit = memory_limit
815
+ self._internal_config.use_cuda_register_memory = hmo.register_cuda_memory
816
+
817
+ # State tracking attributes.
818
+ self.solver_planned = False
819
+ self.solver_factorized = False
820
+
821
+ # Set blocking or non-blocking behavior.
822
+ self.blocking = self.options.blocking is True or self.memory_space == "cpu"
823
+ if self.blocking:
824
+ self.call_prologue = "This call is blocking and will return only after the operation is complete."
825
+ else:
826
+ self.call_prologue = (
827
+ "This call is non-blocking and will return immediately after the operation is launched on the device."
828
+ )
829
+
830
+ # The result (solution) class is that of the wrapped RHS.
831
+ self.result_class = self.b[0].__class__ if self.explicitly_batched_rhs else self.b.__class__
832
+
833
+ # The result shape is a single value or a sequence, depending on whether the RHS
834
+ # is explicitly or implicitly batched as set above.
835
+ self.result_shape = self.rhs_shape
836
+
837
+ # Tracking attributes.
838
+ self.solver_planned = False
839
+ self.solver_factorized = False
840
+
841
+ self.valid_state = True
842
+ self.logger.info("The sparse direct solver operation has been created.")
843
+
844
+ def __enter__(self):
845
+ return self
846
+
847
+ def __exit__(self, exc_type, exc_value, traceback):
848
+ self.free()
849
+
850
+ def _check_valid_solver(self, *args, **kwargs):
851
+ """
852
+ Check if the DirectSolver object is alive and well.
853
+ """
854
+ if not self.valid_state:
855
+ raise InvalidDirectSolverState("The DirectSolver object cannot be used after resources are free'd")
856
+
857
+ def _check_valid_operands(self, *args, **kwargs):
858
+ """
859
+ Check if the operands are available for the operation.
860
+ """
861
+ what = kwargs["what"]
862
+ if self.a is None or self.b is None:
863
+ raise RuntimeError(
864
+ f"{what} cannot be performed if the operands have been set to None. Use reset_operands() to set the "
865
+ f"desired input before using performing the {what.lower()}."
866
+ )
867
+
868
+ def _check_planned(self, *args, **kwargs):
869
+ what = kwargs["what"]
870
+ if not self.solver_planned:
871
+ raise RuntimeError(f"{what} cannot be performed before plan() has been called.")
872
+
873
+ def _check_factorized(self, *args, **kwargs):
874
+ what = kwargs["what"]
875
+ if not self.solver_factorized:
876
+ raise RuntimeError(f"{what} cannot be performed before factorize() has been called.")
877
+
878
+ def _allocate_single_result(self, stream_holder: StreamHolder | None, log_debug):
879
+ if log_debug:
880
+ self.logger.debug("Beginning output (empty) tensor creation...")
881
+ self.logger.debug(
882
+ f"""The output tensor shape = {self.result_shape}, with strides = {self.result_strides}
883
+ and data type '{self.result_data_type}'."""
884
+ )
885
+ result = utils.create_empty_tensor(
886
+ self.result_class,
887
+ self.result_shape,
888
+ self.result_data_type,
889
+ self.result_device_id, # see notes #1 and #2.
890
+ stream_holder=None if self.result_device_id == "cpu" else stream_holder,
891
+ verify_strides=False, # the strides are computed so that they are contiguous
892
+ strides=self.result_strides,
893
+ )
894
+ if log_debug:
895
+ self.logger.debug("The output (empty) tensor has been created.")
896
+ return result
897
+
898
+ def _allocate_batched_result(self, stream_holder: StreamHolder | None, log_debug):
899
+ if log_debug:
900
+ self.logger.debug("Beginning output tensor sequence creation...")
901
+ self.logger.debug(
902
+ f"""The output tensor sequence shape = {self.result_shape}, with strides = {self.result_strides}
903
+ and data type '{self.result_data_type}'."""
904
+ )
905
+ result = tuple(
906
+ utils.create_empty_tensor(
907
+ self.result_class,
908
+ shape,
909
+ self.result_data_type,
910
+ self.result_device_id, # see notes #1 and #2.
911
+ stream_holder=None if self.result_device_id == "cpu" else stream_holder,
912
+ verify_strides=False, # the strides are computed so that they are contiguous
913
+ strides=strides,
914
+ )
915
+ for (shape, strides) in zip(self.result_shape, self.result_strides, strict=True)
916
+ )
917
+
918
+ if log_debug:
919
+ self.logger.debug("The output tensor sequence has been created.")
920
+ return result
921
+
922
+ @property
923
+ def plan_config(self):
924
+ """
925
+ An accessor to configure or query the solver planning phase attributes.
926
+
927
+ Returns:
928
+ A :class:`DirectSolverPlanConfig` object, whose attributes can be set (or
929
+ queried) to configure the planning phase.
930
+
931
+ See Also:
932
+ :class:`DirectSolverPlanConfig`, :meth:`plan`.
933
+ """
934
+ return self._plan_config
935
+
936
+ @property
937
+ def factorization_config(self):
938
+ """
939
+ An accessor to configure or query the solver factorization phase attributes.
940
+
941
+ Returns:
942
+ A :class:`DirectSolverFactorizationConfig` object, whose attributes can be set
943
+ (or queried) to configure the factorization phase.
944
+
945
+ See Also:
946
+ :class:`DirectSolverFactorizationConfig`, :meth:`factorize`.
947
+ """
948
+ return self._factorization_config
949
+
950
+ @property
951
+ def solution_config(self):
952
+ """
953
+ An accessor to configure or query the solver solution phase attributes.
954
+
955
+ Returns:
956
+ A :class:`DirectSolverSolutionConfig` object, whose attributes can be set
957
+ (or queried) to configure the factorization phase.
958
+
959
+ See Also:
960
+ :class:`DirectSolverSolutionConfig`, :meth:`solve`.
961
+ """
962
+ return self._solution_config
963
+
964
+ @property
965
+ def plan_info(self):
966
+ """
967
+ An accessor to get information about the solver planning phase.
968
+
969
+ Returns:
970
+ A :class:`DirectSolverPlanInfo` object, whose attributes can be queried for
971
+ information regarding the planning phase.
972
+
973
+ See Also:
974
+ :class:`DirectSolverPlanInfo`, :meth:`plan`.
975
+ """
976
+ return self._plan_info
977
+
978
+ @property
979
+ def factorization_info(self):
980
+ """
981
+ Query solver factorization information
982
+ (see :class:`nvmath.sparse.advanced.DirectSolverFactorizationInfo`).
983
+ An accessor to get information about the solver factorization phase.
984
+
985
+ Returns:
986
+ A :class:`DirectSolverFactorizationInfo` object, whose attributes can be
987
+ queried for information regarding the factorization phase.
988
+
989
+ See Also:
990
+ :class:`DirectSolverFactorizationInfo`, :meth:`factorize`.
991
+ """
992
+ return self._factorization_info
993
+
994
+ @utils.precondition(_check_valid_solver)
995
+ def reset_operands(
996
+ self,
997
+ a=None,
998
+ b=None,
999
+ *,
1000
+ stream: utils.AnyStream | int | None = None,
1001
+ ):
1002
+ """
1003
+ Reset the operands held by this :class:`DirectSolver` instance.
1004
+
1005
+ This method has two use cases:
1006
+
1007
+ (1) it can be used to provide new operands for execution when the original
1008
+ operands are on the CPU
1009
+
1010
+ (2) it can be used to release the internal reference to the previous operands
1011
+ and make their memory available for other use by passing ``None`` for *all*
1012
+ arguments. In this case, this method must be called again to provide the
1013
+ desired operands before another call to planning and execution APIs like
1014
+ :meth:`plan`, :meth:`factorize`, or :meth:`solve`.
1015
+
1016
+ This method will perform various checks on the new operands to make sure:
1017
+
1018
+ - The shapes, index and data types match those of the old ones.
1019
+
1020
+ - The packages that the operands belong to match those of the old ones.
1021
+
1022
+ - If input tensors are on GPU, the device must match.
1023
+
1024
+ Args:
1025
+ a: {a}
1026
+
1027
+ b: {b}
1028
+
1029
+ stream: {stream}
1030
+
1031
+ Examples:
1032
+
1033
+ >>> import cupy as cp
1034
+ >>> import cupyx.scipy.sparse as sp
1035
+ >>> import nvmath
1036
+
1037
+ Prepare sample input data.
1038
+
1039
+ >>> n = 8
1040
+ >>> a = sp.random(n, n, density=0.15, format="csr", dtype="float64")
1041
+ >>> a += sp.diags([2.0] * n, format="csr", dtype="float64")
1042
+
1043
+ Create the RHS, which can be a matrix or vector in column-major layout.
1044
+
1045
+ >>> b = cp.ones((n,), dtype="float64")
1046
+
1047
+ Specify, plan, factorize and solve a @ x = b. Use the stateful object as a
1048
+ context manager to automatically release resources.
1049
+
1050
+ >>> with nvmath.sparse.advanced.DirectSolver(a, b) as solver:
1051
+ ... # Plan the operation.
1052
+ ... plan_info = solver.plan()
1053
+ ...
1054
+ ... # Factorize the system.
1055
+ ... fac_info = solver.factorize()
1056
+ ...
1057
+ ... # Solve the factorized system for the first result.
1058
+ ... x1 = solver.solve()
1059
+ ...
1060
+ ... # Reset the RHS to a new CuPy ndarray.
1061
+ ... c = cp.random.rand(n, dtype="float64")
1062
+ ... solver.reset_operands(b=c)
1063
+ ...
1064
+ ... # Solve for the second result corresponding to the updated operands.
1065
+ ... x2 = solver.solve()
1066
+
1067
+ .. tip:: If only a subset of operands are reset, the operands that are not
1068
+ reset hold their original values.
1069
+
1070
+ With :meth:`reset_operands`, minimal overhead is achieved as problem
1071
+ specification and planning are only performed once.
1072
+
1073
+ For the particular example above, explicitly calling :meth:`reset_operands` is
1074
+ equivalent to updating the operand `b` in-place, i.e, replacing
1075
+ ``solver.reset_operands(b=c)`` with ``b[:]=c``.
1076
+
1077
+ .. danger:: Updating the operand in-place can only yield the expected result
1078
+ under the additional constraints below:
1079
+
1080
+ - The operand is on the GPU (more precisely, the operand memory space should
1081
+ be accessible from the execution space).
1082
+
1083
+ - The user has called :meth:`factorize` if needed (they are not relying on
1084
+ iterative refinement for example)
1085
+
1086
+ Assuming that the constraint above is satisfied, updating an operand
1087
+ in-place is preferred to avoid the extra checks incurred in
1088
+ :meth:`reset_operands`.
1089
+
1090
+ For more details, please refer to `the reset operand example
1091
+ <https://github.com/NVIDIA/nvmath-python/tree/main/examples/sparse/advanced/direct_solver/example05_reset_operands.py>`_.
1092
+ """
1093
+
1094
+ if a is None and b is None:
1095
+ self.a = self.b = None
1096
+ self.logger.info("The operands have been reset to None.")
1097
+ return
1098
+
1099
+ stream_holder = utils.get_or_create_stream(self.device_id, stream, self.rhs_package)
1100
+
1101
+ # Update LHS.
1102
+ if a is not None:
1103
+ if isinstance(a, Sequence) and not self.explicitly_batched_lhs:
1104
+ raise TypeError("The specified type for 'a` is a sequence while the original type is {type.self.a.tensor}.")
1105
+
1106
+ # Wrap A.
1107
+ try:
1108
+ a = sp_utils.wrap_sparse_operands(a)
1109
+ except Exception as e:
1110
+ raise TypeError(
1111
+ """The LHS 'a' must be an N-D sparse CSR array/tensor or a sequence of 2D sparse CSR array/tensor from one
1112
+ of the supported packages: CuPy, PyTorch, or SciPy."""
1113
+ ) from e
1114
+
1115
+ explicitly_batched = isinstance(a, Sequence)
1116
+ if explicitly_batched:
1117
+ # Successfully wrapping A means that these package is the same for all
1118
+ # sparse operands.
1119
+ lhs_package = utils.infer_object_package(a[0].tensor)
1120
+ # The get_() helpers ensure that the attributes are the same for all
1121
+ # operands.
1122
+ device_id = utils.get_operands_device_id(a)
1123
+ memory_space = a[0].device
1124
+ value_type = utils.get_operands_dtype(a)
1125
+ index_type = sp_utils.get_operands_index_type(a)
1126
+
1127
+ shape = tuple(o.shape for o in a)
1128
+ nnz = tuple(o.values.size for o in a)
1129
+
1130
+ else: # Single or implicitly-batched LHS
1131
+ lhs_package = utils.infer_object_package(a.tensor)
1132
+ device_id = a.device_id
1133
+ memory_space = a.device
1134
+ value_type = a.dtype
1135
+ index_type = a.index_type
1136
+
1137
+ shape = a.shape
1138
+ nnz = a.values.size
1139
+
1140
+ # Check package, device ID, dtype, and index type.
1141
+ if lhs_package != self.lhs_package:
1142
+ raise TypeError("The package for 'a' ({lhs_package}) doesn't match the original one ({self.lhs_package}).")
1143
+
1144
+ if memory_space != self.memory_space:
1145
+ raise TypeError(
1146
+ "The memory space for 'a' ({memory_space}) doesn't match the original one ({self.memory_space})."
1147
+ )
1148
+
1149
+ if device_id != "cpu" and device_id != self.device_id:
1150
+ raise TypeError("The device id for 'a' ({device_id}) doesn't match the original one ({self.device_id}).")
1151
+
1152
+ if value_type != self.value_type:
1153
+ raise TypeError("The dtype for 'a' ({value_type}) doesn't match the original one ({self.value_type}).")
1154
+
1155
+ if index_type != self.index_type:
1156
+ raise TypeError("The index type for 'a' ({index_type}) doesn't match the original one ({self.index_type}).")
1157
+
1158
+ # Checking that the shape is consistent also checks the batch count for both
1159
+ # implicit and explicit batching.
1160
+ if shape != self.lhs_shape:
1161
+ raise TypeError(f"The shape of 'a' ({shape}) doesn't match the original one ({self.lhs_shape}).")
1162
+
1163
+ if nnz != self.lhs_nnz:
1164
+ raise TypeError(f"The number of non-zeros of 'a' ({nnz}) doesn't match the original one ({self.lhs_nnz}).")
1165
+
1166
+ # Copy operand if needed, and replace object reference.
1167
+ if self.copy_across_memspace:
1168
+ # Copy operand into original buffer if it exists or create new ones.
1169
+ log_warning = False
1170
+ if explicitly_batched:
1171
+ if self.a is not None:
1172
+ for x, y in zip(self.a, a, strict=True):
1173
+ x.copy_(y, stream_holder)
1174
+ else:
1175
+ self.a = [x.to(self.device_id, stream_holder) for x in a]
1176
+ log_warning = True
1177
+ else:
1178
+ if self.a is not None:
1179
+ self.a.copy_(a, stream_holder)
1180
+ else:
1181
+ self.a = a.to(self.device_id, stream_holder)
1182
+ log_warning = True
1183
+ if log_warning:
1184
+ self.logger.warning(
1185
+ "The LHS buffer pointers have changed when copying between CPU-GPU, which requires calling \
1186
+ plan() and factorize() again even if the sparsity structure is identical."
1187
+ )
1188
+ else:
1189
+ # Invalidate the plan, since the buffer pointers could have changed.
1190
+ self.solver_planned = self.solver_factorized = False
1191
+ self.logger.warning(
1192
+ "The specified LHS may have different buffers for the compressed row or column indices \
1193
+ or values, which requires calling plan() and factorize() again even if the sparsity structure is identical. To avoid this, it \
1194
+ is recommended to update the values in place and refactorize if needed."
1195
+ )
1196
+ self.a = a
1197
+
1198
+ # Update the pointer references, and keep reference to the internal buffers.
1199
+ self.resources_ra = cudss_utils.update_cudss_csr_ptr_wrapper(
1200
+ self.a_ptr, batch_indices=self.batch_indices, new_lhs=self.a, stream_holder=stream_holder
1201
+ )
1202
+
1203
+ self.logger.warning(
1204
+ "Resetting the LHS 'a' typically requires calling factorize() again. An exception is the use of \
1205
+ iterative refinement during solve(), but it's the user's responsibility to check that the solution has converged."
1206
+ )
1207
+
1208
+ # Update RHS.
1209
+ if b is not None:
1210
+ # Wrap b.
1211
+ explicitly_batched = isinstance(b, Sequence)
1212
+ if explicitly_batched:
1213
+ b = tensor_wrapper.wrap_operands(b)
1214
+ rhs_package = utils.get_operands_package(b)
1215
+
1216
+ # The get_() helpers ensure that the attributes are the same for all
1217
+ # operands.
1218
+ device_id = utils.get_operands_device_id(b)
1219
+ memory_space = b[0].device
1220
+ value_type = utils.get_operands_dtype(b)
1221
+ shape = tuple(o.shape for o in b)
1222
+ strides = tuple(o.strides for o in b)
1223
+ else: # Single or implicitly-batched RHS
1224
+ b = tensor_wrapper.wrap_operand(b)
1225
+ rhs_package = utils.infer_object_package(b.tensor)
1226
+
1227
+ device_id = b.device_id
1228
+ memory_space = b.device
1229
+ value_type = b.dtype
1230
+ shape = b.shape
1231
+ strides = b.strides
1232
+
1233
+ # Handle cupy <> numpy asymmetry. See note #2.
1234
+ if rhs_package == "numpy":
1235
+ rhs_package = "cupy"
1236
+
1237
+ # Check package, device ID, shape, strides, and dtype.
1238
+ if rhs_package != self.rhs_package:
1239
+ raise TypeError(f"The package for 'b' ({rhs_package}) doesn't match the original one ({self.rhs_package}).")
1240
+
1241
+ if memory_space != self.memory_space:
1242
+ raise TypeError(
1243
+ f"The memory space for 'b' ({memory_space}) doesn't match the original one ({self.memory_space})."
1244
+ )
1245
+
1246
+ if device_id != "cpu" and device_id != self.device_id:
1247
+ raise TypeError(f"The device id for 'b' ({device_id}) doesn't match the original one ({self.device_id}).")
1248
+
1249
+ if value_type != self.value_type:
1250
+ raise TypeError(f"The dtype for 'b' ({value_type}) doesn't match the original one ({self.value_type}).")
1251
+
1252
+ # Checking that the shape is consistent also checks the batch count for both
1253
+ # implicit and explicit batching.
1254
+ if shape != self.rhs_shape:
1255
+ raise TypeError(f"The shape of 'b' ({shape}) doesn't match the original one ({self.rhs_shape}).")
1256
+
1257
+ if strides != self.rhs_strides:
1258
+ raise TypeError(f"The strides of 'b' ({strides}) don't match the original one ({self.rhs_strides}).")
1259
+
1260
+ # Copy operand if needed, and replace object reference.
1261
+ # Copy operand if needed, and replace object reference.
1262
+ if self.copy_across_memspace:
1263
+ # Copy operand into original buffer if it exists or create new ones.
1264
+ if explicitly_batched:
1265
+ if self.b is not None:
1266
+ for x, y in zip(self.b, b, strict=True):
1267
+ x.copy_(y, stream_holder)
1268
+ else:
1269
+ self.b = [x.to(self.device_id, stream_holder) for x in b]
1270
+ else:
1271
+ if self.b is not None:
1272
+ self.b.copy_(b, stream_holder)
1273
+ else:
1274
+ self.b = b.to(self.device_id, stream_holder)
1275
+ else:
1276
+ self.b = b
1277
+
1278
+ # Update the pointer references, and keep reference to the internal buffers.
1279
+ self.resources_rb = cudss_utils.update_cudss_dense_ptr_wrapper(
1280
+ self.b_ptr, batch_indices=self.batch_indices, new_rhs=self.b, stream_holder=stream_holder
1281
+ )
1282
+
1283
+ @utils.precondition(_check_valid_solver)
1284
+ @utils.precondition(_check_valid_operands, "Planning")
1285
+ def plan(self, *, stream: utils.AnyStream | None = None):
1286
+ """
1287
+ Plan the sparse direct solve (reordering to minimize fill-in, and symbolic
1288
+ factorization). The planning phase can be optionally configured through
1289
+ the property :attr:`plan_config` (an object of type
1290
+ :class:`DirectSolverPlanConfig`). Planning returns a :class:`DirectSolverPlanInfo`
1291
+ object, which can also be accessed through the property :attr:`plan_info`.
1292
+
1293
+ Args:
1294
+ stream: {stream}
1295
+
1296
+ Returns:
1297
+ A :class:`DirectSolverPlanInfo` object, whose attributes can be queried for
1298
+ information regarding the plan.
1299
+
1300
+ See Also:
1301
+ :attr:`plan_config`, :class:`DirectSolverPlanConfig`,
1302
+ :class:`DirectSolverPlanInfo`.
1303
+
1304
+ Examples:
1305
+
1306
+ >>> import cupy as cp
1307
+ >>> import cupyx.scipy.sparse as sp
1308
+ >>> import nvmath
1309
+
1310
+ Prepare sample input data.
1311
+
1312
+ >>> n = 8
1313
+ >>> a = sp.random(n, n, density=0.5, format="csr", dtype="float64")
1314
+ >>> a += sp.diags([2.0] * n, format="csr", dtype="float64")
1315
+
1316
+ Create the RHS, which can be a matrix or vector in column-major layout.
1317
+
1318
+ >>> b = cp.ones((n,), dtype="float64")
1319
+
1320
+ Specify, configure, and plan a @ x = b. Use the stateful object as a context
1321
+ manager to automatically release resources.
1322
+
1323
+ >>> with nvmath.sparse.advanced.DirectSolver(a, b) as solver:
1324
+ ... # Configure the reordering algorithm for the plan.
1325
+ ... plan_config = solver.plan_config
1326
+ ... plan_config.algorithm = nvmath.sparse.advanced.DirectSolverAlgType.ALG_1
1327
+ ... # Plan the operation using the specified plan configuration, which
1328
+ ... # returns a DirectSolverPlanInfo object.
1329
+ ... plan_info = solver.plan()
1330
+ ... # Query the column permutation, memory estimates, ...
1331
+ ... plan_info.col_permutation
1332
+ array([6, 1, 4, 0, 3, 2, 5, 7], dtype=int32)
1333
+
1334
+ Further examples can be found in the `nvmath/examples/sparse/advanced/direct_solver
1335
+ <https://github.com/NVIDIA/nvmath-python/tree/main/examples/sparse/advanced/direct_solver>`_
1336
+ directory.
1337
+ """
1338
+ r = self._execute(phase=cudss.Phase.ANALYSIS, stream=stream)
1339
+ self.solver_planned = True
1340
+ return r
1341
+
1342
+ @utils.precondition(_check_valid_solver)
1343
+ @utils.precondition(_check_planned, "Factorization")
1344
+ @utils.precondition(_check_valid_operands, "Factorization")
1345
+ def factorize(self, *, stream: utils.AnyStream | None = None):
1346
+ """
1347
+ Factorize the system of equations. Numerical factorization is required each time
1348
+ the values in the LHS change, unless (for example) iterative refinement is used
1349
+ during the solve and it converges (see :attr:`solution_config`).
1350
+
1351
+ This phase can be optionally configured through the property
1352
+ :attr:`factorization_config` (an object of type
1353
+ :class:`DirectSolverFactorizationConfig`). Factorization returns a
1354
+ :class:`DirectSolverFactorizationInfo` object, which can also be accessed through
1355
+ the property :attr:`factorization_info`.
1356
+
1357
+ Args:
1358
+ stream: {stream}
1359
+
1360
+ Returns:
1361
+ A :class:`DirectSolverFactorizationInfo` object, whose attributes can be
1362
+ queried for information regarding the numerical factorization.
1363
+
1364
+ See Also:
1365
+ :attr:`factorization_config`, :class:`DirectSolverFactorizationConfig`,
1366
+ :class:`DirectSolverFactorizationInfo`.
1367
+
1368
+ Examples:
1369
+
1370
+ >>> import cupy as cp
1371
+ >>> import cupyx.scipy.sparse as sp
1372
+ >>> import nvmath
1373
+
1374
+ Prepare sample input data.
1375
+
1376
+ >>> n = 8
1377
+ >>> a = sp.random(n, n, density=0.25, format="csr", dtype="float64")
1378
+ >>> a += sp.diags([2.0] * n, format="csr", dtype="float64")
1379
+
1380
+ Create the RHS, which can be a matrix or vector in column-major layout.
1381
+
1382
+ >>> b = cp.ones((n, 2), dtype="float64", order="F")
1383
+
1384
+ Specify, plan, and factorize a @ x = b. Use the stateful object as a context
1385
+ manager to automatically release resources.
1386
+
1387
+ >>> with nvmath.sparse.advanced.DirectSolver(a, b) as solver:
1388
+ ... # Plan the operation (configure if desired).
1389
+ ... plan_info = solver.plan()
1390
+ ... # (Optionally) configure the factorization.
1391
+ ... fac_config = solver.factorization_config
1392
+ ... fac_config.pivot_eps = 1e-14
1393
+ ... # Factorize using the specified factorization configuration, which
1394
+ ... # returns a DirectSolverFactorizationInfo object.
1395
+ ... fac_info = solver.factorize()
1396
+ ... # Query the number of non-zeros, inertia, ...
1397
+ ... fac_info.lu_nnz
1398
+ 40
1399
+
1400
+ Further examples can be found in the `nvmath/examples/sparse/advanced/direct_solver
1401
+ <https://github.com/NVIDIA/nvmath-python/tree/main/examples/sparse/advanced/direct_solver>`_
1402
+ directory.
1403
+ """
1404
+ r = self._execute(phase=cudss.Phase.FACTORIZATION, stream=stream)
1405
+ self.solver_factorized = True
1406
+ return r
1407
+
1408
+ @utils.precondition(_check_valid_solver)
1409
+ @utils.precondition(_check_planned, "Solver")
1410
+ @utils.precondition(_check_factorized, "Solver")
1411
+ @utils.precondition(_check_valid_operands, "Solver")
1412
+ def solve(self, *, stream: utils.AnyStream | None = None):
1413
+ """
1414
+ Solve the factorized system of equations.
1415
+
1416
+ This phase can be optionally configured through the property
1417
+ :attr:`solution_config` (an object of type
1418
+ :class:`DirectSolverSolutionConfig`).
1419
+
1420
+ Args:
1421
+ stream: {stream}
1422
+
1423
+ Returns:
1424
+ {result}
1425
+
1426
+ See Also:
1427
+ :attr:`solution_config`, :class:`DirectSolverSolutionConfig`.
1428
+
1429
+ Examples:
1430
+
1431
+ >>> import cupy as cp
1432
+ >>> import cupyx.scipy.sparse as sp
1433
+ >>> import nvmath
1434
+
1435
+ Prepare sample input data.
1436
+
1437
+ >>> n = 8
1438
+ >>> a = sp.random(n, n, density=0.25, format="csr", dtype="float64")
1439
+ >>> a += sp.diags([2.0] * n, format="csr", dtype="float64")
1440
+
1441
+ Create the RHS, which can be a matrix or vector in column-major layout.
1442
+
1443
+ >>> b = cp.ones((n, 2), dtype="float64", order="F")
1444
+
1445
+ Specify, plan, factorize, and solve a @ x = b for x. Use the stateful
1446
+ object as a context manager to automatically release resources.
1447
+
1448
+ >>> with nvmath.sparse.advanced.DirectSolver(a, b) as solver:
1449
+ ... # Plan the operation (configure if desired).
1450
+ ... plan_info = solver.plan()
1451
+ ... # Factorize the system (configure if desired).
1452
+ ... fac_info = solver.factorize()
1453
+ ... # (Optionally) configure the solve.
1454
+ ... solution_config = solver.solution_config
1455
+ ... solution_config.ir_num_steps = 10
1456
+ ... # Solve the system based on the solution configuration set above.
1457
+ ... x = solver.solve()
1458
+
1459
+ Further examples can be found in the `nvmath/examples/sparse/advanced/direct_solver
1460
+ <https://github.com/NVIDIA/nvmath-python/tree/main/examples/sparse/advanced/direct_solver>`_
1461
+ directory.
1462
+ """
1463
+ return self._execute(phase=cudss.Phase.SOLVE, stream=stream)
1464
+
1465
+ def _execute(self, *, phase=None, stream=None):
1466
+ """
1467
+ For internal use only. Execute the specified operation (reordering, factorization,
1468
+ and solve).
1469
+
1470
+ Args:
1471
+ phase: The operation phase (as Python `int` or enumeration of type Phase).
1472
+
1473
+ stream: {stream}
1474
+
1475
+ Returns:
1476
+ {plan|factorization]_info object for reordering and factorization, and the
1477
+ solution in the expected memory space for solve.
1478
+ """
1479
+
1480
+ assert phase is not None, "Internal error."
1481
+
1482
+ log_info = self.logger.isEnabledFor(logging.INFO)
1483
+ log_debug = self.logger.isEnabledFor(logging.DEBUG)
1484
+
1485
+ stream_holder = utils.get_or_create_stream(self.device_id, stream, self.rhs_package)
1486
+
1487
+ cudss.set_stream(self.handle, stream_holder.ptr)
1488
+
1489
+ # Allocate result for only the solve phase and update the pointer.
1490
+ result = None
1491
+ if phase == cudss.Phase.SOLVE:
1492
+ # The result can be either a single tensor or a sequence of tensors, depending
1493
+ # on whether the RHS is explicitly batched.
1494
+ result_allocator = self._allocate_batched_result if self.explicitly_batched_rhs else self._allocate_single_result
1495
+ result = result_allocator(stream_holder, log_debug)
1496
+ cudss_utils.update_cudss_dense_ptr_wrapper(
1497
+ self.x_ptr, batch_indices=self.batch_indices, new_rhs=result, stream_holder=stream_holder
1498
+ )
1499
+
1500
+ if log_info:
1501
+ self.logger.info(f"Starting solver phase {phase.name}...")
1502
+ self.logger.info(f"{self.call_prologue}")
1503
+
1504
+ with utils.cuda_call_ctx(stream_holder, self.blocking, timing=log_info) as (
1505
+ self.last_compute_event,
1506
+ elapsed,
1507
+ ):
1508
+ cudss.execute(self.handle, phase, self.config_ptr, self.data_ptr, self.a_ptr, self.x_ptr, self.b_ptr)
1509
+
1510
+ if log_info and elapsed.data is not None:
1511
+ self.logger.info(f"The solver phase {phase.name} took {elapsed.data:.3f} ms to complete.")
1512
+
1513
+ if phase == cudss.Phase.ANALYSIS:
1514
+ return self.plan_info
1515
+
1516
+ if phase == cudss.Phase.FACTORIZATION:
1517
+ return self.factorization_info
1518
+
1519
+ # Ideally, we should set the x_ptr to 0, but this adds overhead for the batched
1520
+ # case.
1521
+
1522
+ # Copy result to required memory spaces if needed.
1523
+ if self.copy_across_memspace:
1524
+ result = copy_single_or_sequence(result, "cpu", stream_holder)
1525
+
1526
+ # Extract the result tensor from the wrapped result for the solution phase.
1527
+ if isinstance(result, Sequence):
1528
+ out = tuple(r.tensor for r in result)
1529
+ else:
1530
+ out = result.tensor
1531
+
1532
+ return out
1533
+
1534
+ def free(self):
1535
+ """Free DirectSolver resources.
1536
+
1537
+ It is recommended that the :class:`DirectSolver` object be used within a context,
1538
+ but if it is not possible then this method must be called explicitly to ensure
1539
+ that the sparse direct solver resources (especially internal library objects) are
1540
+ properly cleaned up.
1541
+ """
1542
+
1543
+ if not self.valid_state:
1544
+ return
1545
+
1546
+ try:
1547
+ # Currently, workspace is allocated internally by the library.
1548
+
1549
+ # Release internal resource references.
1550
+ self.resources_a = self.resources_b = self.resources_x = None
1551
+ self.resources_ra = self.resources_rb = None
1552
+
1553
+ # Free matrix pointers.
1554
+ cudss.matrix_destroy(self.x_ptr)
1555
+ cudss.matrix_destroy(self.b_ptr)
1556
+ cudss.matrix_destroy(self.a_ptr)
1557
+ self.x_ptr = self.b_ptr = self.a_ptr = None
1558
+
1559
+ # Free config and data pointers.
1560
+ cudss.data_destroy(self.handle, self.data_ptr)
1561
+ cudss.config_destroy(self.config_ptr)
1562
+ self.data_ptr = self.config_ptr = None
1563
+
1564
+ # Free handle if we own it.
1565
+ if self.handle is not None and self.own_handle:
1566
+ cudss.destroy(self.handle)
1567
+ self.handle, self.own_handle = None, False
1568
+
1569
+ except Exception as e:
1570
+ self.logger.critical("Internal error: only part of the DirectSolver object's resources have been released.")
1571
+ self.logger.critical(str(e))
1572
+ raise e
1573
+ finally:
1574
+ self.valid_state = False
1575
+
1576
+ self.logger.info("The DirectSolver object's resources have been released.")
1577
+
1578
+
1579
+ @utils.docstring_decorator(SHARED_DSS_DOCUMENTATION, skip_missing=False)
1580
+ def direct_solver(
1581
+ a,
1582
+ b,
1583
+ /,
1584
+ *,
1585
+ options: DirectSolverOptions | None = None,
1586
+ execution: ExecutionCUDA | ExecutionHybrid | None = None,
1587
+ stream: utils.AnyStream | int | None = None,
1588
+ ):
1589
+ """
1590
+ Solve :math:`a @ x = b` for :math:`x`. This function-form API is a wrapper around the
1591
+ stateful :class:`DirectSolver` object APIs and is meant for *single* use (the user needs
1592
+ to perform just one sparse direct solve, for example), in which case there is no
1593
+ possibility of amortizing preparatory costs.
1594
+
1595
+ Detailed information on what's happening within this function can be obtained by passing
1596
+ in a :class:`logging.Logger` object to :class:`DirectSolverOptions` or by setting the
1597
+ appropriate options in the root logger object, which is used by default:
1598
+
1599
+ >>> import logging
1600
+ >>> logging.basicConfig(
1601
+ ... level=logging.INFO,
1602
+ ... format="%(asctime)s %(levelname)-8s %(message)s",
1603
+ ... datefmt="%m-%d %H:%M:%S",
1604
+ ... )
1605
+
1606
+ A user can select the desired logging level and, in general, take advantage of all of
1607
+ the functionality offered by the Python :mod:`logging` module.
1608
+
1609
+ Args:
1610
+ a: {a}
1611
+
1612
+ b: {b}
1613
+
1614
+ options: {options}
1615
+
1616
+ execution: {execution}
1617
+
1618
+ stream: {stream}
1619
+
1620
+ Returns:
1621
+ {result}
1622
+
1623
+ .. _Semantics:
1624
+
1625
+ Semantics:
1626
+ {semantics}
1627
+
1628
+ See Also:
1629
+ :class:`DirectSolver`, :class:`DirectSolverOptions`, :class:`ExecutionCUDA`,
1630
+ :class:`ExecutionHybrid`.
1631
+
1632
+ Examples:
1633
+
1634
+ >>> import cupy as cp
1635
+ >>> import cupyx.scipy.sparse as sp
1636
+ >>> import nvmath
1637
+
1638
+ Create a sparse float32 ndarray in CSR format on the CPU for the LHS.
1639
+
1640
+ >>> n = 16
1641
+ >>> a = sp.random(n, n, density=0.5, format="csr", dtype="float32")
1642
+
1643
+ Ensure that the randomly-generated LHS is not singular.
1644
+
1645
+ >>> a += sp.diags([2.0] * n, format="csr", dtype="float32")
1646
+
1647
+ The RHS can be a vector or matrix. Here we create a random matrix with 4 columns
1648
+ (indicating 4 vectors to be solved for) in column-major format.
1649
+
1650
+ >>> b = cp.random.rand(4, n, dtype="float32").T
1651
+
1652
+ Solve a @ x = b for x.
1653
+
1654
+ >>> x = nvmath.sparse.advanced.direct_solver(a, b)
1655
+
1656
+ Batching can be specified, explicitly or implicitly, following the semantics
1657
+ described above. Here we explicitly batch the LHS since CuPy doesn't support 3D CSR,
1658
+ while we implicitly batch the RHS.
1659
+
1660
+ Create an explicit batch of two CSR matrices:
1661
+
1662
+ >>> batch = 2
1663
+ >>> a = [a] * batch
1664
+ >>> a[1] *= 10.0
1665
+
1666
+ Create a 3D ndarray, with each sample in the batch having column-major layout.
1667
+
1668
+ >>> b = cp.random.rand(batch, 4, n, dtype="float32").transpose(0, 2, 1)
1669
+
1670
+ Solve the batched system a @ x = b for x, where x has the same shape as b.
1671
+
1672
+ >>> x = nvmath.sparse.advanced.direct_solver(a, b)
1673
+
1674
+ Options can be provided to the sparse direct solver using
1675
+ :class:`DirectSolverOptions`, and the execution space can be specified using the
1676
+ ``execution`` option. Refer to :class:`DirectSolver` and the GitHub link below for
1677
+ examples.
1678
+
1679
+ Notes:
1680
+
1681
+ - This function is a convenience wrapper around :class:`DirectSolver` and is
1682
+ specifically meant for *single* use.
1683
+
1684
+ Further examples can be found in the `nvmath/examples/sparse/advanced/direct_solver
1685
+ <https://github.com/NVIDIA/nvmath-python/tree/main/examples/sparse/advanced/direct_solver>`_
1686
+ directory.
1687
+ """
1688
+
1689
+ with DirectSolver(
1690
+ a,
1691
+ b,
1692
+ options=options,
1693
+ execution=execution,
1694
+ stream=stream,
1695
+ ) as solver:
1696
+ # Planning and factorization information cannot be returned without making copies
1697
+ # because of scope (the interfaces need the solver object, which is released when
1698
+ # the function returns).
1699
+ solver.plan(stream=stream)
1700
+
1701
+ solver.factorize(stream=stream)
1702
+
1703
+ r = solver.solve(stream=stream)
1704
+
1705
+ return r