xref: /petsc/src/mat/impls/dense/seq/cupm/matseqdensecupm.hpp (revision cc7980154d91e4d53ff48c8dc1d2bc5deb304502)
1 #pragma once
2 
3 #include <petsc/private/matdensecupmimpl.h> /*I <petscmat.h> I*/
4 #include <../src/mat/impls/dense/seq/dense.h>
5 
6 #include <petsc/private/deviceimpl.h> // PetscDeviceContextGetOptionalNullContext_Internal()
7 #include <petsc/private/randomimpl.h> // _p_PetscRandom
8 #include <petsc/private/vecimpl.h>    // _p_Vec
9 #include <petsc/private/cupmobject.hpp>
10 #include <petsc/private/cupmsolverinterface.hpp>
11 
12 #include <petsc/private/cpp/type_traits.hpp> // PetscObjectCast()
13 #include <petsc/private/cpp/utility.hpp>     // util::exchange()
14 
15 #include <../src/vec/vec/impls/seq/cupm/vecseqcupm.hpp> // for VecSeq_CUPM
16 
17 namespace Petsc
18 {
19 
20 namespace mat
21 {
22 
23 namespace cupm
24 {
25 
26 namespace impl
27 {
28 
29 template <device::cupm::DeviceType T>
30 class MatDense_Seq_CUPM : MatDense_CUPM<T, MatDense_Seq_CUPM<T>> {
31 public:
32   MATDENSECUPM_HEADER(T, MatDense_Seq_CUPM<T>);
33 
34 private:
35   struct Mat_SeqDenseCUPM {
36     PetscScalar *d_v;           // pointer to the matrix on the GPU
37     PetscScalar *unplacedarray; // if one called MatCUPMDensePlaceArray(), this is where it stashed the original
38     bool         d_user_alloc;
39     bool         d_unplaced_user_alloc;
40     // factorization support
41     cupmBlasInt_t *d_fact_ipiv;  // device pivots
42     cupmScalar_t  *d_fact_tau;   // device QR tau vector
43     cupmBlasInt_t *d_fact_info;  // device info
44     cupmScalar_t  *d_fact_work;  // device workspace
45     cupmBlasInt_t  d_fact_lwork; // size of device workspace
46     // workspace
47     Vec workvec;
48   };
49 
50   static PetscErrorCode SetPreallocation_(Mat, PetscDeviceContext, PetscScalar *) noexcept;
51 
52   static PetscErrorCode HostToDevice_(Mat, PetscDeviceContext) noexcept;
53   static PetscErrorCode DeviceToHost_(Mat, PetscDeviceContext) noexcept;
54 
55   static PetscErrorCode CheckCUPMSolverInfo_(const cupmBlasInt_t *, cupmStream_t) noexcept;
56 
57   template <typename Derived>
58   struct SolveCommon;
59   struct SolveQR;
60   struct SolveCholesky;
61   struct SolveLU;
62 
63   template <typename Solver, bool transpose>
64   static PetscErrorCode MatSolve_Factored_Dispatch_(Mat, Vec, Vec) noexcept;
65   template <typename Solver, bool transpose>
66   static PetscErrorCode MatMatSolve_Factored_Dispatch_(Mat, Mat, Mat) noexcept;
67   template <bool transpose, bool hermitian>
68   static PetscErrorCode MatMultAdd_Dispatch_(Mat, Vec, Vec, Vec) noexcept;
69 
70   template <bool to_host>
71   static PetscErrorCode Convert_Dispatch_(Mat, MatType, MatReuse, Mat *) noexcept;
72 
73   PETSC_NODISCARD static constexpr MatType       MATIMPLCUPM_() noexcept;
74   PETSC_NODISCARD static constexpr Mat_SeqDense *MatIMPLCast_(Mat) noexcept;
75 
76 public:
77   PETSC_NODISCARD static constexpr Mat_SeqDenseCUPM *MatCUPMCast(Mat) noexcept;
78 
79   // define these by hand since they don't fit the above mold
80   PETSC_NODISCARD static constexpr const char *MatConvert_seqdensecupm_seqdense_C() noexcept;
81   PETSC_NODISCARD static constexpr const char *MatProductSetFromOptions_seqaij_seqdensecupm_C() noexcept;
82 
83   static PetscErrorCode Create(Mat) noexcept;
84   static PetscErrorCode Destroy(Mat) noexcept;
85   static PetscErrorCode SetUp(Mat) noexcept;
86   static PetscErrorCode Reset(Mat) noexcept;
87 
88   static PetscErrorCode BindToCPU(Mat, PetscBool) noexcept;
89   static PetscErrorCode Convert_SeqDense_SeqDenseCUPM(Mat, MatType, MatReuse, Mat *) noexcept;
90   static PetscErrorCode Convert_SeqDenseCUPM_SeqDense(Mat, MatType, MatReuse, Mat *) noexcept;
91 
92   template <PetscMemType, PetscMemoryAccessMode>
93   static PetscErrorCode GetArray(Mat, PetscScalar **, PetscDeviceContext) noexcept;
94   template <PetscMemType, PetscMemoryAccessMode>
95   static PetscErrorCode RestoreArray(Mat, PetscScalar **, PetscDeviceContext) noexcept;
96   template <PetscMemoryAccessMode>
97   static PetscErrorCode GetArrayAndMemType(Mat, PetscScalar **, PetscMemType *, PetscDeviceContext) noexcept;
98   template <PetscMemoryAccessMode>
99   static PetscErrorCode RestoreArrayAndMemType(Mat, PetscScalar **, PetscDeviceContext) noexcept;
100 
101 private:
102   template <PetscMemType mtype, PetscMemoryAccessMode mode>
103   static PetscErrorCode GetArrayC_(Mat m, PetscScalar **p) noexcept
104   {
105     PetscDeviceContext dctx;
106 
107     PetscFunctionBegin;
108     PetscCall(GetHandles_(&dctx));
109     PetscCall(GetArray<mtype, mode>(m, p, dctx));
110     PetscFunctionReturn(PETSC_SUCCESS);
111   }
112 
113   template <PetscMemType mtype, PetscMemoryAccessMode mode>
114   static PetscErrorCode RestoreArrayC_(Mat m, PetscScalar **p) noexcept
115   {
116     PetscDeviceContext dctx;
117 
118     PetscFunctionBegin;
119     PetscCall(GetHandles_(&dctx));
120     PetscCall(RestoreArray<mtype, mode>(m, p, dctx));
121     PetscFunctionReturn(PETSC_SUCCESS);
122   }
123 
124   template <PetscMemoryAccessMode mode>
125   static PetscErrorCode GetArrayAndMemTypeC_(Mat m, PetscScalar **p, PetscMemType *tp) noexcept
126   {
127     PetscDeviceContext dctx;
128 
129     PetscFunctionBegin;
130     PetscCall(GetHandles_(&dctx));
131     PetscCall(GetArrayAndMemType<mode>(m, p, tp, dctx));
132     PetscFunctionReturn(PETSC_SUCCESS);
133   }
134 
135   template <PetscMemoryAccessMode mode>
136   static PetscErrorCode RestoreArrayAndMemTypeC_(Mat m, PetscScalar **p) noexcept
137   {
138     PetscDeviceContext dctx;
139 
140     PetscFunctionBegin;
141     PetscCall(GetHandles_(&dctx));
142     PetscCall(RestoreArrayAndMemType<mode>(m, p, dctx));
143     PetscFunctionReturn(PETSC_SUCCESS);
144   }
145 
146 public:
147   static PetscErrorCode PlaceArray(Mat, const PetscScalar *) noexcept;
148   static PetscErrorCode ReplaceArray(Mat, const PetscScalar *) noexcept;
149   static PetscErrorCode ResetArray(Mat) noexcept;
150 
151   template <bool transpose_A, bool transpose_B>
152   static PetscErrorCode MatMatMult_Numeric_Dispatch(Mat, Mat, Mat) noexcept;
153   static PetscErrorCode Copy(Mat, Mat, MatStructure) noexcept;
154   static PetscErrorCode ZeroEntries(Mat) noexcept;
155   static PetscErrorCode Scale(Mat, PetscScalar) noexcept;
156   static PetscErrorCode AXPY(Mat, PetscScalar, Mat, MatStructure) noexcept;
157   static PetscErrorCode Duplicate(Mat, MatDuplicateOption, Mat *) noexcept;
158   static PetscErrorCode SetRandom(Mat, PetscRandom) noexcept;
159 
160   static PetscErrorCode GetColumnVector(Mat, Vec, PetscInt) noexcept;
161   template <PetscMemoryAccessMode>
162   static PetscErrorCode GetColumnVec(Mat, PetscInt, Vec *) noexcept;
163   template <PetscMemoryAccessMode>
164   static PetscErrorCode RestoreColumnVec(Mat, PetscInt, Vec *) noexcept;
165 
166   static PetscErrorCode GetFactor(Mat, MatFactorType, Mat *) noexcept;
167   static PetscErrorCode InvertFactors(Mat) noexcept;
168 
169   static PetscErrorCode GetSubMatrix(Mat, PetscInt, PetscInt, PetscInt, PetscInt, Mat *) noexcept;
170   static PetscErrorCode RestoreSubMatrix(Mat, Mat *) noexcept;
171 };
172 
173 } // namespace impl
174 
175 namespace
176 {
177 
178 // Declare this here so that the functions below can make use of it
179 template <device::cupm::DeviceType T>
180 inline PetscErrorCode MatCreateSeqDenseCUPM(MPI_Comm comm, PetscInt m, PetscInt n, PetscScalar *data, Mat *A, PetscDeviceContext dctx = nullptr, bool preallocate = true) noexcept
181 {
182   PetscFunctionBegin;
183   PetscCall(impl::MatDense_Seq_CUPM<T>::CreateIMPLDenseCUPM(comm, m, n, m, n, data, A, dctx, preallocate));
184   PetscFunctionReturn(PETSC_SUCCESS);
185 }
186 
187 } // anonymous namespace
188 
189 namespace impl
190 {
191 
192 // ==========================================================================================
193 // MatDense_Seq_CUPM - Private API - Utility
194 // ==========================================================================================
195 
196 template <device::cupm::DeviceType T>
197 inline PetscErrorCode MatDense_Seq_CUPM<T>::SetPreallocation_(Mat m, PetscDeviceContext dctx, PetscScalar *user_device_array) noexcept
198 {
199   const auto   mcu   = MatCUPMCast(m);
200   const auto   nrows = m->rmap->n;
201   const auto   ncols = m->cmap->n;
202   auto        &lda   = MatIMPLCast(m)->lda;
203   cupmStream_t stream;
204 
205   PetscFunctionBegin;
206   PetscCheckTypeName(m, MATSEQDENSECUPM());
207   PetscValidDeviceContext(dctx, 2);
208   PetscCall(checkCupmBlasIntCast(nrows));
209   PetscCall(checkCupmBlasIntCast(ncols));
210   PetscCall(GetHandlesFrom_(dctx, &stream));
211   if (lda <= 0) lda = nrows;
212   if (!mcu->d_user_alloc) PetscCallCUPM(cupmFreeAsync(mcu->d_v, stream));
213   if (user_device_array) {
214     mcu->d_user_alloc = PETSC_TRUE;
215     mcu->d_v          = user_device_array;
216   } else {
217     PetscInt size;
218 
219     mcu->d_user_alloc = PETSC_FALSE;
220     PetscCall(PetscIntMultError(lda, ncols, &size));
221     PetscCall(PetscCUPMMallocAsync(&mcu->d_v, size, stream));
222     PetscCall(PetscCUPMMemsetAsync(mcu->d_v, 0, size, stream));
223   }
224   m->offloadmask = PETSC_OFFLOAD_GPU;
225   PetscFunctionReturn(PETSC_SUCCESS);
226 }
227 
228 template <device::cupm::DeviceType T>
229 inline PetscErrorCode MatDense_Seq_CUPM<T>::HostToDevice_(Mat m, PetscDeviceContext dctx) noexcept
230 {
231   const auto nrows = m->rmap->n;
232   const auto ncols = m->cmap->n;
233   const auto copy  = m->offloadmask == PETSC_OFFLOAD_CPU || m->offloadmask == PETSC_OFFLOAD_UNALLOCATED;
234 
235   PetscFunctionBegin;
236   PetscCheckTypeName(m, MATSEQDENSECUPM());
237   if (m->boundtocpu) PetscFunctionReturn(PETSC_SUCCESS);
238   PetscCall(PetscInfo(m, "%s matrix %" PetscInt_FMT " x %" PetscInt_FMT "\n", copy ? "Copy" : "Reusing", nrows, ncols));
239   if (copy) {
240     const auto   mcu = MatCUPMCast(m);
241     cupmStream_t stream;
242 
243     // Allocate GPU memory if not present
244     if (!mcu->d_v) PetscCall(SetPreallocation(m, dctx, nullptr));
245     PetscCall(GetHandlesFrom_(dctx, &stream));
246     PetscCall(PetscLogEventBegin(MAT_DenseCopyToGPU, m, 0, 0, 0));
247     {
248       const auto mimpl = MatIMPLCast(m);
249       const auto lda   = mimpl->lda;
250       const auto src   = mimpl->v;
251       const auto dest  = mcu->d_v;
252 
253       if (lda > nrows) {
254         PetscCall(PetscCUPMMemcpy2DAsync(dest, lda, src, lda, nrows, ncols, cupmMemcpyHostToDevice, stream));
255       } else {
256         PetscCall(PetscCUPMMemcpyAsync(dest, src, lda * ncols, cupmMemcpyHostToDevice, stream));
257       }
258     }
259     PetscCall(PetscLogEventEnd(MAT_DenseCopyToGPU, m, 0, 0, 0));
260     // order important, ensure that offloadmask is PETSC_OFFLOAD_BOTH
261     m->offloadmask = PETSC_OFFLOAD_BOTH;
262   }
263   PetscFunctionReturn(PETSC_SUCCESS);
264 }
265 
266 template <device::cupm::DeviceType T>
267 inline PetscErrorCode MatDense_Seq_CUPM<T>::DeviceToHost_(Mat m, PetscDeviceContext dctx) noexcept
268 {
269   const auto nrows = m->rmap->n;
270   const auto ncols = m->cmap->n;
271   const auto copy  = m->offloadmask == PETSC_OFFLOAD_GPU;
272 
273   PetscFunctionBegin;
274   PetscCheckTypeName(m, MATSEQDENSECUPM());
275   PetscCall(PetscInfo(m, "%s matrix %" PetscInt_FMT " x %" PetscInt_FMT "\n", copy ? "Copy" : "Reusing", nrows, ncols));
276   if (copy) {
277     const auto   mimpl = MatIMPLCast(m);
278     cupmStream_t stream;
279 
280     // MatCreateSeqDenseCUPM may not allocate CPU memory. Allocate if needed
281     if (!mimpl->v) PetscCall(MatSeqDenseSetPreallocation(m, nullptr));
282     PetscCall(GetHandlesFrom_(dctx, &stream));
283     PetscCall(PetscLogEventBegin(MAT_DenseCopyFromGPU, m, 0, 0, 0));
284     {
285       const auto lda  = mimpl->lda;
286       const auto dest = mimpl->v;
287       const auto src  = MatCUPMCast(m)->d_v;
288 
289       if (lda > nrows) {
290         PetscCall(PetscCUPMMemcpy2DAsync(dest, lda, src, lda, nrows, ncols, cupmMemcpyDeviceToHost, stream));
291       } else {
292         PetscCall(PetscCUPMMemcpyAsync(dest, src, lda * ncols, cupmMemcpyDeviceToHost, stream));
293       }
294     }
295     PetscCall(PetscLogEventEnd(MAT_DenseCopyFromGPU, m, 0, 0, 0));
296     // order is important, MatSeqDenseSetPreallocation() might set offloadmask
297     m->offloadmask = PETSC_OFFLOAD_BOTH;
298   }
299   PetscFunctionReturn(PETSC_SUCCESS);
300 }
301 
302 template <device::cupm::DeviceType T>
303 inline PetscErrorCode MatDense_Seq_CUPM<T>::CheckCUPMSolverInfo_(const cupmBlasInt_t *fact_info, cupmStream_t stream) noexcept
304 {
305   PetscFunctionBegin;
306   if (PetscDefined(USE_DEBUG)) {
307     cupmBlasInt_t info = 0;
308 
309     PetscCall(PetscCUPMMemcpyAsync(&info, fact_info, 1, cupmMemcpyDeviceToHost, stream));
310     if (stream) PetscCallCUPM(cupmStreamSynchronize(stream));
311     static_assert(std::is_same<decltype(info), int>::value, "");
312     PetscCheck(info <= 0, PETSC_COMM_SELF, PETSC_ERR_MAT_CH_ZRPVT, "Bad factorization: zero pivot in row %d", info - 1);
313     PetscCheck(info >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Wrong argument to cupmSolver %d", -info);
314   }
315   PetscFunctionReturn(PETSC_SUCCESS);
316 }
317 
318 // ==========================================================================================
319 // MatDense_Seq_CUPM - Private API - Solver Dispatch
320 // ==========================================================================================
321 
322 // specific solvers called through the dispatch_() family of functions
323 template <device::cupm::DeviceType T>
324 template <typename Derived>
325 struct MatDense_Seq_CUPM<T>::SolveCommon {
326   using derived_type = Derived;
327 
328   template <typename F>
329   static PetscErrorCode ResizeFactLwork(Mat_SeqDenseCUPM *mcu, cupmStream_t stream, F &&cupmSolverComputeFactLwork) noexcept
330   {
331     cupmBlasInt_t lwork;
332 
333     PetscFunctionBegin;
334     PetscCallCUPMSOLVER(cupmSolverComputeFactLwork(&lwork));
335     if (lwork > mcu->d_fact_lwork) {
336       mcu->d_fact_lwork = lwork;
337       PetscCallCUPM(cupmFreeAsync(mcu->d_fact_work, stream));
338       PetscCall(PetscCUPMMallocAsync(&mcu->d_fact_work, lwork, stream));
339     }
340     PetscFunctionReturn(PETSC_SUCCESS);
341   }
342 
343   static PetscErrorCode FactorPrepare(Mat A, cupmStream_t stream) noexcept
344   {
345     const auto mcu = MatCUPMCast(A);
346 
347     PetscFunctionBegin;
348     PetscCall(PetscInfo(A, "%s factor %" PetscInt_FMT " x %" PetscInt_FMT " on backend\n", derived_type::NAME(), A->rmap->n, A->cmap->n));
349     A->factortype             = derived_type::MATFACTORTYPE();
350     A->ops->solve             = MatSolve_Factored_Dispatch_<derived_type, false>;
351     A->ops->solvetranspose    = MatSolve_Factored_Dispatch_<derived_type, true>;
352     A->ops->matsolve          = MatMatSolve_Factored_Dispatch_<derived_type, false>;
353     A->ops->matsolvetranspose = MatMatSolve_Factored_Dispatch_<derived_type, true>;
354 
355     PetscCall(PetscStrFreeAllocpy(MATSOLVERCUPM(), &A->solvertype));
356     if (!mcu->d_fact_info) PetscCall(PetscCUPMMallocAsync(&mcu->d_fact_info, 1, stream));
357     PetscFunctionReturn(PETSC_SUCCESS);
358   }
359 };
360 
361 template <device::cupm::DeviceType T>
362 struct MatDense_Seq_CUPM<T>::SolveLU : SolveCommon<SolveLU> {
363   using base_type = SolveCommon<SolveLU>;
364 
365   static constexpr const char   *NAME() noexcept { return "LU"; }
366   static constexpr MatFactorType MATFACTORTYPE() noexcept { return MAT_FACTOR_LU; }
367 
368   static PetscErrorCode Factor(Mat A, IS, IS, const MatFactorInfo *) noexcept
369   {
370     const auto         m = static_cast<cupmBlasInt_t>(A->rmap->n);
371     const auto         n = static_cast<cupmBlasInt_t>(A->cmap->n);
372     cupmStream_t       stream;
373     cupmSolverHandle_t handle;
374     PetscDeviceContext dctx;
375 
376     PetscFunctionBegin;
377     if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS);
378     PetscCall(GetHandles_(&dctx, &handle, &stream));
379     PetscCall(base_type::FactorPrepare(A, stream));
380     {
381       const auto mcu = MatCUPMCast(A);
382       const auto da  = DeviceArrayReadWrite(dctx, A);
383       const auto lda = static_cast<cupmBlasInt_t>(MatIMPLCast(A)->lda);
384 
385       // clang-format off
386       PetscCall(
387         base_type::ResizeFactLwork(
388           mcu, stream,
389           [&](cupmBlasInt_t *fact_lwork)
390           {
391             return cupmSolverXgetrf_bufferSize(handle, m, n, da.cupmdata(), lda, fact_lwork);
392           }
393         )
394       );
395       // clang-format on
396       if (!mcu->d_fact_ipiv) PetscCall(PetscCUPMMallocAsync(&mcu->d_fact_ipiv, n, stream));
397 
398       PetscCall(PetscLogGpuTimeBegin());
399       PetscCallCUPMSOLVER(cupmSolverXgetrf(handle, m, n, da.cupmdata(), lda, mcu->d_fact_work, mcu->d_fact_lwork, mcu->d_fact_ipiv, mcu->d_fact_info));
400       PetscCall(PetscLogGpuTimeEnd());
401       PetscCall(CheckCUPMSolverInfo_(mcu->d_fact_info, stream));
402     }
403     PetscCall(PetscLogGpuFlops(2.0 * n * n * m / 3.0));
404     PetscFunctionReturn(PETSC_SUCCESS);
405   }
406 
407   template <bool transpose>
408   static PetscErrorCode Solve(Mat A, cupmScalar_t *x, cupmBlasInt_t ldx, cupmBlasInt_t m, cupmBlasInt_t nrhs, cupmBlasInt_t k, PetscDeviceContext dctx, cupmStream_t stream) noexcept
409   {
410     const auto         mcu       = MatCUPMCast(A);
411     const auto         fact_info = mcu->d_fact_info;
412     const auto         fact_ipiv = mcu->d_fact_ipiv;
413     cupmSolverHandle_t handle;
414 
415     PetscFunctionBegin;
416     PetscCall(GetHandlesFrom_(dctx, &handle));
417     PetscCall(PetscInfo(A, "%s solve %d x %d on backend\n", NAME(), m, k));
418     PetscCall(PetscLogGpuTimeBegin());
419     {
420       constexpr auto op  = transpose ? CUPMSOLVER_OP_T : CUPMSOLVER_OP_N;
421       const auto     da  = DeviceArrayRead(dctx, A);
422       const auto     lda = static_cast<cupmBlasInt_t>(MatIMPLCast(A)->lda);
423 
424       // clang-format off
425       PetscCall(
426         base_type::ResizeFactLwork(
427           mcu, stream,
428           [&](cupmBlasInt_t *lwork)
429           {
430             return cupmSolverXgetrs_bufferSize(
431               handle, op, m, nrhs, da.cupmdata(), lda, fact_ipiv, x, ldx, lwork
432             );
433           }
434         )
435       );
436       // clang-format on
437       PetscCallCUPMSOLVER(cupmSolverXgetrs(handle, op, m, nrhs, da.cupmdata(), lda, fact_ipiv, x, ldx, mcu->d_fact_work, mcu->d_fact_lwork, fact_info));
438       PetscCall(CheckCUPMSolverInfo_(fact_info, stream));
439     }
440     PetscCall(PetscLogGpuTimeEnd());
441     PetscCall(PetscLogGpuFlops(nrhs * (2.0 * m * m - m)));
442     PetscFunctionReturn(PETSC_SUCCESS);
443   }
444 };
445 
446 template <device::cupm::DeviceType T>
447 struct MatDense_Seq_CUPM<T>::SolveCholesky : SolveCommon<SolveCholesky> {
448   using base_type = SolveCommon<SolveCholesky>;
449 
450   static constexpr const char   *NAME() noexcept { return "Cholesky"; }
451   static constexpr MatFactorType MATFACTORTYPE() noexcept { return MAT_FACTOR_CHOLESKY; }
452 
453   static PetscErrorCode Factor(Mat A, IS, const MatFactorInfo *) noexcept
454   {
455     const auto         n = static_cast<cupmBlasInt_t>(A->rmap->n);
456     PetscDeviceContext dctx;
457     cupmSolverHandle_t handle;
458     cupmStream_t       stream;
459 
460     PetscFunctionBegin;
461     if (!n || !A->cmap->n) PetscFunctionReturn(PETSC_SUCCESS);
462     PetscCheck(A->spd == PETSC_BOOL3_TRUE, PETSC_COMM_SELF, PETSC_ERR_SUP, "%ssytrs unavailable. Use MAT_FACTOR_LU", cupmSolverName());
463     PetscCall(GetHandles_(&dctx, &handle, &stream));
464     PetscCall(base_type::FactorPrepare(A, stream));
465     {
466       const auto mcu = MatCUPMCast(A);
467       const auto da  = DeviceArrayReadWrite(dctx, A);
468       const auto lda = static_cast<cupmBlasInt_t>(MatIMPLCast(A)->lda);
469 
470       // clang-format off
471       PetscCall(
472         base_type::ResizeFactLwork(
473           mcu, stream,
474           [&](cupmBlasInt_t *fact_lwork)
475           {
476             return cupmSolverXpotrf_bufferSize(
477               handle, CUPMSOLVER_FILL_MODE_LOWER, n, da.cupmdata(), lda, fact_lwork
478             );
479           }
480         )
481       );
482       // clang-format on
483       PetscCall(PetscLogGpuTimeBegin());
484       PetscCallCUPMSOLVER(cupmSolverXpotrf(handle, CUPMSOLVER_FILL_MODE_LOWER, n, da.cupmdata(), lda, mcu->d_fact_work, mcu->d_fact_lwork, mcu->d_fact_info));
485       PetscCall(PetscLogGpuTimeEnd());
486       PetscCall(CheckCUPMSolverInfo_(mcu->d_fact_info, stream));
487     }
488     PetscCall(PetscLogGpuFlops(1.0 * n * n * n / 3.0));
489 
490 #if 0
491     // At the time of writing this interface (cuda 10.0), cusolverDn does not implement *sytrs
492     // and *hetr* routines. The code below should work, and it can be activated when *sytrs
493     // routines will be available
494     if (!mcu->d_fact_ipiv) PetscCall(PetscCUPMMallocAsync(&mcu->d_fact_ipiv, n, stream));
495     if (!mcu->d_fact_lwork) {
496       PetscCallCUPMSOLVER(cupmSolverDnXsytrf_bufferSize(handle, n, da.cupmdata(), lda, &mcu->d_fact_lwork));
497       PetscCall(PetscCUPMMallocAsync(&mcu->d_fact_work, mcu->d_fact_lwork, stream));
498     }
499     if (mcu->d_fact_info) PetscCall(PetscCUPMMallocAsync(&mcu->d_fact_info, 1, stream));
500     PetscCall(PetscLogGpuTimeBegin());
501     PetscCallCUPMSOLVER(cupmSolverXsytrf(handle, CUPMSOLVER_FILL_MODE_LOWER, n, da, lda, mcu->d_fact_ipiv, mcu->d_fact_work, mcu->d_fact_lwork, mcu->d_fact_info));
502     PetscCall(PetscLogGpuTimeEnd());
503 #endif
504     PetscFunctionReturn(PETSC_SUCCESS);
505   }
506 
507   template <bool transpose>
508   static PetscErrorCode Solve(Mat A, cupmScalar_t *x, cupmBlasInt_t ldx, cupmBlasInt_t m, cupmBlasInt_t nrhs, cupmBlasInt_t k, PetscDeviceContext dctx, cupmStream_t stream) noexcept
509   {
510     const auto         mcu       = MatCUPMCast(A);
511     const auto         fact_info = mcu->d_fact_info;
512     cupmSolverHandle_t handle;
513 
514     PetscFunctionBegin;
515     PetscAssert(!mcu->d_fact_ipiv, PETSC_COMM_SELF, PETSC_ERR_LIB, "%ssytrs not implemented", cupmSolverName());
516     PetscCall(GetHandlesFrom_(dctx, &handle));
517     PetscCall(PetscInfo(A, "%s solve %d x %d on backend\n", NAME(), m, k));
518     PetscCall(PetscLogGpuTimeBegin());
519     {
520       const auto da  = DeviceArrayRead(dctx, A);
521       const auto lda = static_cast<cupmBlasInt_t>(MatIMPLCast(A)->lda);
522 
523       // clang-format off
524       PetscCall(
525         base_type::ResizeFactLwork(
526           mcu, stream,
527           [&](cupmBlasInt_t *lwork)
528           {
529             return cupmSolverXpotrs_bufferSize(
530               handle, CUPMSOLVER_FILL_MODE_LOWER, m, nrhs, da.cupmdata(), lda, x, ldx, lwork
531             );
532           }
533         )
534       );
535       // clang-format on
536       PetscCallCUPMSOLVER(cupmSolverXpotrs(handle, CUPMSOLVER_FILL_MODE_LOWER, m, nrhs, da.cupmdata(), lda, x, ldx, mcu->d_fact_work, mcu->d_fact_lwork, fact_info));
537       PetscCall(CheckCUPMSolverInfo_(fact_info, stream));
538     }
539     PetscCall(PetscLogGpuTimeEnd());
540     PetscCall(PetscLogGpuFlops(nrhs * (2.0 * m * m - m)));
541     PetscFunctionReturn(PETSC_SUCCESS);
542   }
543 };
544 
545 template <device::cupm::DeviceType T>
546 struct MatDense_Seq_CUPM<T>::SolveQR : SolveCommon<SolveQR> {
547   using base_type = SolveCommon<SolveQR>;
548 
549   static constexpr const char   *NAME() noexcept { return "QR"; }
550   static constexpr MatFactorType MATFACTORTYPE() noexcept { return MAT_FACTOR_QR; }
551 
552   static PetscErrorCode Factor(Mat A, IS, const MatFactorInfo *) noexcept
553   {
554     const auto         m     = static_cast<cupmBlasInt_t>(A->rmap->n);
555     const auto         n     = static_cast<cupmBlasInt_t>(A->cmap->n);
556     const auto         min   = std::min(m, n);
557     const auto         mimpl = MatIMPLCast(A);
558     cupmStream_t       stream;
559     cupmSolverHandle_t handle;
560     PetscDeviceContext dctx;
561 
562     PetscFunctionBegin;
563     if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS);
564     PetscCall(GetHandles_(&dctx, &handle, &stream));
565     PetscCall(base_type::FactorPrepare(A, stream));
566     mimpl->rank = min;
567     {
568       const auto mcu = MatCUPMCast(A);
569       const auto da  = DeviceArrayReadWrite(dctx, A);
570       const auto lda = static_cast<cupmBlasInt_t>(mimpl->lda);
571 
572       if (!mcu->workvec) PetscCall(vec::cupm::VecCreateSeqCUPMAsync<T>(PetscObjectComm(PetscObjectCast(A)), m, &mcu->workvec));
573       if (!mcu->d_fact_tau) PetscCall(PetscCUPMMallocAsync(&mcu->d_fact_tau, min, stream));
574       // clang-format off
575       PetscCall(
576         base_type::ResizeFactLwork(
577           mcu, stream,
578           [&](cupmBlasInt_t *fact_lwork)
579           {
580             return cupmSolverXgeqrf_bufferSize(handle, m, n, da.cupmdata(), lda, fact_lwork);
581           }
582         )
583       );
584       // clang-format on
585       PetscCall(PetscLogGpuTimeBegin());
586       PetscCallCUPMSOLVER(cupmSolverXgeqrf(handle, m, n, da.cupmdata(), lda, mcu->d_fact_tau, mcu->d_fact_work, mcu->d_fact_lwork, mcu->d_fact_info));
587       PetscCall(PetscLogGpuTimeEnd());
588       PetscCall(CheckCUPMSolverInfo_(mcu->d_fact_info, stream));
589     }
590     PetscCall(PetscLogGpuFlops(2.0 * min * min * (std::max(m, n) - min / 3.0)));
591     PetscFunctionReturn(PETSC_SUCCESS);
592   }
593 
594   template <bool transpose>
595   static PetscErrorCode Solve(Mat A, cupmScalar_t *x, cupmBlasInt_t ldx, cupmBlasInt_t m, cupmBlasInt_t nrhs, cupmBlasInt_t k, PetscDeviceContext dctx, cupmStream_t stream) noexcept
596   {
597     const auto         mimpl      = MatIMPLCast(A);
598     const auto         rank       = static_cast<cupmBlasInt_t>(mimpl->rank);
599     const auto         mcu        = MatCUPMCast(A);
600     const auto         fact_info  = mcu->d_fact_info;
601     const auto         fact_tau   = mcu->d_fact_tau;
602     const auto         fact_work  = mcu->d_fact_work;
603     const auto         fact_lwork = mcu->d_fact_lwork;
604     cupmSolverHandle_t solver_handle;
605     cupmBlasHandle_t   blas_handle;
606 
607     PetscFunctionBegin;
608     PetscCall(GetHandlesFrom_(dctx, &blas_handle, &solver_handle));
609     PetscCall(PetscInfo(A, "%s solve %d x %d on backend\n", NAME(), m, k));
610     PetscCall(PetscLogGpuTimeBegin());
611     {
612       const auto da  = DeviceArrayRead(dctx, A);
613       const auto one = cupmScalarCast(1.0);
614       const auto lda = static_cast<cupmBlasInt_t>(mimpl->lda);
615 
616       if (transpose) {
617         PetscCallCUPMBLAS(cupmBlasXtrsm(blas_handle, CUPMBLAS_SIDE_LEFT, CUPMBLAS_FILL_MODE_UPPER, CUPMBLAS_OP_T, CUPMBLAS_DIAG_NON_UNIT, rank, nrhs, &one, da.cupmdata(), lda, x, ldx));
618         PetscCallCUPMSOLVER(cupmSolverXormqr(solver_handle, CUPMSOLVER_SIDE_LEFT, CUPMSOLVER_OP_N, m, nrhs, rank, da.cupmdata(), lda, fact_tau, x, ldx, fact_work, fact_lwork, fact_info));
619         PetscCall(CheckCUPMSolverInfo_(fact_info, stream));
620       } else {
621         constexpr auto op = PetscDefined(USE_COMPLEX) ? CUPMSOLVER_OP_C : CUPMSOLVER_OP_T;
622 
623         PetscCallCUPMSOLVER(cupmSolverXormqr(solver_handle, CUPMSOLVER_SIDE_LEFT, op, m, nrhs, rank, da.cupmdata(), lda, fact_tau, x, ldx, fact_work, fact_lwork, fact_info));
624         PetscCall(CheckCUPMSolverInfo_(fact_info, stream));
625         PetscCallCUPMBLAS(cupmBlasXtrsm(blas_handle, CUPMBLAS_SIDE_LEFT, CUPMBLAS_FILL_MODE_UPPER, CUPMBLAS_OP_N, CUPMBLAS_DIAG_NON_UNIT, rank, nrhs, &one, da.cupmdata(), lda, x, ldx));
626       }
627     }
628     PetscCall(PetscLogGpuTimeEnd());
629     PetscCall(PetscLogFlops(nrhs * (4.0 * m * rank - (rank * rank))));
630     PetscFunctionReturn(PETSC_SUCCESS);
631   }
632 };
633 
634 template <device::cupm::DeviceType T>
635 template <typename Solver, bool transpose>
636 inline PetscErrorCode MatDense_Seq_CUPM<T>::MatSolve_Factored_Dispatch_(Mat A, Vec x, Vec y) noexcept
637 {
638   using namespace vec::cupm;
639   const auto         pobj_A  = PetscObjectCast(A);
640   const auto         m       = static_cast<cupmBlasInt_t>(A->rmap->n);
641   const auto         k       = static_cast<cupmBlasInt_t>(A->cmap->n);
642   auto              &workvec = MatCUPMCast(A)->workvec;
643   PetscScalar       *y_array = nullptr;
644   PetscDeviceContext dctx;
645   PetscBool          xiscupm, yiscupm, aiscupm;
646   bool               use_y_array_directly;
647   cupmStream_t       stream;
648 
649   PetscFunctionBegin;
650   PetscCheck(A->factortype != MAT_FACTOR_NONE, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Matrix must be factored to solve");
651   PetscCall(PetscObjectTypeCompare(PetscObjectCast(x), VecSeq_CUPM::VECSEQCUPM(), &xiscupm));
652   PetscCall(PetscObjectTypeCompare(PetscObjectCast(y), VecSeq_CUPM::VECSEQCUPM(), &yiscupm));
653   PetscCall(PetscObjectTypeCompare(pobj_A, MATSEQDENSECUPM(), &aiscupm));
654   PetscAssert(aiscupm, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Matrix A is somehow not CUPM?????????????????????????????");
655   PetscCall(GetHandles_(&dctx, &stream));
656   use_y_array_directly = yiscupm && (k >= m);
657   {
658     const PetscScalar *x_array;
659     const auto         xisdevice = xiscupm && PetscOffloadDevice(x->offloadmask);
660     const auto         copy_mode = xisdevice ? cupmMemcpyDeviceToDevice : cupmMemcpyHostToDevice;
661 
662     if (!use_y_array_directly && !workvec) PetscCall(VecCreateSeqCUPMAsync<T>(PetscObjectComm(pobj_A), m, &workvec));
663     // The logic here is to try to minimize the amount of memory copying:
664     //
665     // If we call VecCUPMGetArrayRead(X, &x) every time xiscupm and the data is not offloaded
666     // to the GPU yet, then the data is copied to the GPU. But we are only trying to get the
667     // data in order to copy it into the y array. So the array x will be wherever the data
668     // already is so that only one memcpy is performed
669     if (xisdevice) {
670       PetscCall(VecCUPMGetArrayReadAsync<T>(x, &x_array, dctx));
671     } else {
672       PetscCall(VecGetArrayRead(x, &x_array));
673     }
674     PetscCall(VecCUPMGetArrayWriteAsync<T>(use_y_array_directly ? y : workvec, &y_array, dctx));
675     PetscCall(PetscCUPMMemcpyAsync(y_array, x_array, m, copy_mode, stream));
676     if (xisdevice) {
677       PetscCall(VecCUPMRestoreArrayReadAsync<T>(x, &x_array, dctx));
678     } else {
679       PetscCall(VecRestoreArrayRead(x, &x_array));
680     }
681   }
682 
683   if (!aiscupm) PetscCall(MatConvert(A, MATSEQDENSECUPM(), MAT_INPLACE_MATRIX, &A));
684   PetscCall(Solver{}.template Solve<transpose>(A, cupmScalarPtrCast(y_array), m, m, 1, k, dctx, stream));
685   if (!aiscupm) PetscCall(MatConvert(A, MATSEQDENSE, MAT_INPLACE_MATRIX, &A));
686 
687   if (use_y_array_directly) {
688     PetscCall(VecCUPMRestoreArrayWriteAsync<T>(y, &y_array, dctx));
689   } else {
690     const auto   copy_mode = yiscupm ? cupmMemcpyDeviceToDevice : cupmMemcpyDeviceToHost;
691     PetscScalar *yv;
692 
693     // The logic here is that the data is not yet in either y's GPU array or its CPU array.
694     // There is nothing in the interface to say where the user would like it to end up. So we
695     // choose the GPU, because it is the faster option
696     if (yiscupm) {
697       PetscCall(VecCUPMGetArrayWriteAsync<T>(y, &yv, dctx));
698     } else {
699       PetscCall(VecGetArray(y, &yv));
700     }
701     PetscCall(PetscCUPMMemcpyAsync(yv, y_array, k, copy_mode, stream));
702     if (yiscupm) {
703       PetscCall(VecCUPMRestoreArrayWriteAsync<T>(y, &yv, dctx));
704     } else {
705       PetscCall(VecRestoreArray(y, &yv));
706     }
707     PetscCall(VecCUPMRestoreArrayWriteAsync<T>(workvec, &y_array));
708   }
709   PetscFunctionReturn(PETSC_SUCCESS);
710 }
711 
712 template <device::cupm::DeviceType T>
713 template <typename Solver, bool transpose>
714 inline PetscErrorCode MatDense_Seq_CUPM<T>::MatMatSolve_Factored_Dispatch_(Mat A, Mat B, Mat X) noexcept
715 {
716   const auto         m = static_cast<cupmBlasInt_t>(A->rmap->n);
717   const auto         k = static_cast<cupmBlasInt_t>(A->cmap->n);
718   cupmBlasInt_t      nrhs, ldb, ldx, ldy;
719   PetscScalar       *y;
720   PetscBool          biscupm, xiscupm, aiscupm;
721   PetscDeviceContext dctx;
722   cupmStream_t       stream;
723 
724   PetscFunctionBegin;
725   PetscCheck(A->factortype != MAT_FACTOR_NONE, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Matrix must be factored to solve");
726   PetscCall(PetscObjectTypeCompare(PetscObjectCast(B), MATSEQDENSECUPM(), &biscupm));
727   PetscCall(PetscObjectTypeCompare(PetscObjectCast(X), MATSEQDENSECUPM(), &xiscupm));
728   PetscCall(PetscObjectTypeCompare(PetscObjectCast(A), MATSEQDENSECUPM(), &aiscupm));
729   PetscCall(GetHandles_(&dctx, &stream));
730   {
731     PetscInt n;
732 
733     PetscCall(MatGetSize(B, nullptr, &n));
734     PetscCall(PetscCUPMBlasIntCast(n, &nrhs));
735     PetscCall(MatDenseGetLDA(B, &n));
736     PetscCall(PetscCUPMBlasIntCast(n, &ldb));
737     PetscCall(MatDenseGetLDA(X, &n));
738     PetscCall(PetscCUPMBlasIntCast(n, &ldx));
739   }
740   {
741     // The logic here is to try to minimize the amount of memory copying:
742     //
743     // If we call MatDenseCUPMGetArrayRead(B, &b) every time biscupm and the data is not
744     // offloaded to the GPU yet, then the data is copied to the GPU. But we are only trying to
745     // get the data in order to copy it into the y array. So the array b will be wherever the
746     // data already is so that only one memcpy is performed
747     const auto         bisdevice = biscupm && PetscOffloadDevice(B->offloadmask);
748     const auto         copy_mode = bisdevice ? cupmMemcpyDeviceToDevice : cupmMemcpyHostToDevice;
749     const PetscScalar *b;
750 
751     if (bisdevice) {
752       b = DeviceArrayRead(dctx, B);
753     } else if (biscupm) {
754       b = HostArrayRead(dctx, B);
755     } else {
756       PetscCall(MatDenseGetArrayRead(B, &b));
757     }
758 
759     if (ldx < m || !xiscupm) {
760       // X's array cannot serve as the array (too small or not on device), B's array cannot
761       // serve as the array (const), so allocate a new array
762       ldy = m;
763       PetscCall(PetscCUPMMallocAsync(&y, nrhs * m));
764     } else {
765       // X's array should serve as the array
766       ldy = ldx;
767       y   = DeviceArrayWrite(dctx, X);
768     }
769     PetscCall(PetscCUPMMemcpy2DAsync(y, ldy, b, ldb, m, nrhs, copy_mode, stream));
770     if (!bisdevice && !biscupm) PetscCall(MatDenseRestoreArrayRead(B, &b));
771   }
772 
773   // convert to CUPM twice??????????????????????????????????
774   // but A should already be CUPM??????????????????????????????????????
775   if (!aiscupm) PetscCall(MatConvert(A, MATSEQDENSECUPM(), MAT_INPLACE_MATRIX, &A));
776   PetscCall(Solver{}.template Solve<transpose>(A, cupmScalarPtrCast(y), ldy, m, nrhs, k, dctx, stream));
777   if (!aiscupm) PetscCall(MatConvert(A, MATSEQDENSECUPM(), MAT_INPLACE_MATRIX, &A));
778 
779   if (ldx < m || !xiscupm) {
780     const auto   copy_mode = xiscupm ? cupmMemcpyDeviceToDevice : cupmMemcpyDeviceToHost;
781     PetscScalar *x;
782 
783     // The logic here is that the data is not yet in either X's GPU array or its CPU
784     // array. There is nothing in the interface to say where the user would like it to end up.
785     // So we choose the GPU, because it is the faster option
786     if (xiscupm) {
787       x = DeviceArrayWrite(dctx, X);
788     } else {
789       PetscCall(MatDenseGetArray(X, &x));
790     }
791     PetscCall(PetscCUPMMemcpy2DAsync(x, ldx, y, ldy, k, nrhs, copy_mode, stream));
792     if (!xiscupm) PetscCall(MatDenseRestoreArray(X, &x));
793     PetscCallCUPM(cupmFreeAsync(y, stream));
794   }
795   PetscFunctionReturn(PETSC_SUCCESS);
796 }
797 
798 template <device::cupm::DeviceType T>
799 template <bool transpose, bool hermitian>
800 inline PetscErrorCode MatDense_Seq_CUPM<T>::MatMultAdd_Dispatch_(Mat A, Vec xx, Vec yy, Vec zz) noexcept
801 {
802   const auto         m = static_cast<cupmBlasInt_t>(A->rmap->n);
803   const auto         n = static_cast<cupmBlasInt_t>(A->cmap->n);
804   cupmBlasHandle_t   handle;
805   PetscDeviceContext dctx;
806 
807   PetscFunctionBegin;
808   if (yy && yy != zz) PetscCall(VecSeq_CUPM::Copy(yy, zz)); // mult add
809   if (!m || !n) {
810     // mult only
811     if (!yy) PetscCall(VecSeq_CUPM::Set(zz, 0.0));
812     PetscFunctionReturn(PETSC_SUCCESS);
813   }
814   PetscCall(PetscInfo(A, "Matrix-vector product %" PetscBLASInt_FMT " x %" PetscBLASInt_FMT " on backend\n", m, n));
815   PetscCall(GetHandles_(&dctx, &handle));
816   {
817     constexpr auto op   = transpose ? (hermitian ? CUPMBLAS_OP_C : CUPMBLAS_OP_T) : CUPMBLAS_OP_N;
818     const auto     one  = cupmScalarCast(1.0);
819     const auto     zero = cupmScalarCast(0.0);
820     const auto     da   = DeviceArrayRead(dctx, A);
821     const auto     dxx  = VecSeq_CUPM::DeviceArrayRead(dctx, xx);
822     const auto     dzz  = VecSeq_CUPM::DeviceArrayReadWrite(dctx, zz);
823 
824     PetscCall(PetscLogGpuTimeBegin());
825     PetscCallCUPMBLAS(cupmBlasXgemv(handle, op, m, n, &one, da.cupmdata(), static_cast<cupmBlasInt_t>(MatIMPLCast(A)->lda), dxx.cupmdata(), 1, (yy ? &one : &zero), dzz.cupmdata(), 1));
826     PetscCall(PetscLogGpuTimeEnd());
827   }
828   PetscCall(PetscLogGpuFlops(2.0 * m * n - (yy ? 0 : m)));
829   PetscFunctionReturn(PETSC_SUCCESS);
830 }
831 
832 // ==========================================================================================
833 // MatDense_Seq_CUPM - Private API - Conversion Dispatch
834 // ==========================================================================================
835 
836 template <device::cupm::DeviceType T>
837 template <bool to_host>
838 inline PetscErrorCode MatDense_Seq_CUPM<T>::Convert_Dispatch_(Mat M, MatType type, MatReuse reuse, Mat *newmat) noexcept
839 {
840   PetscFunctionBegin;
841   if (reuse == MAT_REUSE_MATRIX || reuse == MAT_INITIAL_MATRIX) {
842     // TODO these cases should be optimized
843     PetscCall(MatConvert_Basic(M, type, reuse, newmat));
844   } else {
845     const auto B    = *newmat;
846     const auto pobj = PetscObjectCast(B);
847 
848     if (to_host) {
849       PetscCall(BindToCPU(B, PETSC_TRUE));
850       PetscCall(Reset(B));
851     } else {
852       PetscCall(PetscDeviceInitialize(PETSC_DEVICE_CUPM()));
853     }
854 
855     PetscCall(PetscStrFreeAllocpy(to_host ? VECSTANDARD : VecSeq_CUPM::VECCUPM(), &B->defaultvectype));
856     PetscCall(PetscObjectChangeTypeName(pobj, to_host ? MATSEQDENSE : MATSEQDENSECUPM()));
857     // cvec might be the wrong VecType, destroy and rebuild it if necessary
858     // REVIEW ME: this is possibly very inefficient
859     PetscCall(VecDestroy(&MatIMPLCast(B)->cvec));
860 
861     MatComposeOp_CUPM(to_host, pobj, MatConvert_seqdensecupm_seqdense_C(), nullptr, Convert_SeqDenseCUPM_SeqDense);
862     MatComposeOp_CUPM(to_host, pobj, MatDenseCUPMGetArray_C(), nullptr, GetArrayC_<PETSC_MEMTYPE_DEVICE, PETSC_MEMORY_ACCESS_READ_WRITE>);
863     MatComposeOp_CUPM(to_host, pobj, MatDenseCUPMGetArrayRead_C(), nullptr, GetArrayC_<PETSC_MEMTYPE_DEVICE, PETSC_MEMORY_ACCESS_READ>);
864     MatComposeOp_CUPM(to_host, pobj, MatDenseCUPMGetArrayWrite_C(), nullptr, GetArrayC_<PETSC_MEMTYPE_DEVICE, PETSC_MEMORY_ACCESS_WRITE>);
865     MatComposeOp_CUPM(to_host, pobj, MatDenseCUPMRestoreArray_C(), nullptr, RestoreArrayC_<PETSC_MEMTYPE_DEVICE, PETSC_MEMORY_ACCESS_READ_WRITE>);
866     MatComposeOp_CUPM(to_host, pobj, MatDenseCUPMRestoreArrayRead_C(), nullptr, RestoreArrayC_<PETSC_MEMTYPE_DEVICE, PETSC_MEMORY_ACCESS_READ>);
867     MatComposeOp_CUPM(to_host, pobj, MatDenseCUPMRestoreArrayWrite_C(), nullptr, RestoreArrayC_<PETSC_MEMTYPE_DEVICE, PETSC_MEMORY_ACCESS_WRITE>);
868     MatComposeOp_CUPM(to_host, pobj, MatDenseCUPMPlaceArray_C(), nullptr, PlaceArray);
869     MatComposeOp_CUPM(to_host, pobj, MatDenseCUPMResetArray_C(), nullptr, ResetArray);
870     MatComposeOp_CUPM(to_host, pobj, MatDenseCUPMReplaceArray_C(), nullptr, ReplaceArray);
871     MatComposeOp_CUPM(to_host, pobj, MatProductSetFromOptions_seqaij_seqdensecupm_C(), nullptr, MatProductSetFromOptions_SeqAIJ_SeqDense);
872     MatComposeOp_CUPM(to_host, pobj, MatDenseCUPMSetPreallocation_C(), nullptr, SetPreallocation);
873 
874     if (to_host) {
875       B->offloadmask = PETSC_OFFLOAD_CPU;
876     } else {
877       Mat_SeqDenseCUPM *mcu;
878 
879       PetscCall(PetscNew(&mcu));
880       B->spptr       = mcu;
881       B->offloadmask = PETSC_OFFLOAD_UNALLOCATED; // REVIEW ME: why not offload host??
882       PetscCall(BindToCPU(B, PETSC_FALSE));
883     }
884 
885     MatSetOp_CUPM(to_host, B, bindtocpu, nullptr, BindToCPU);
886     MatSetOp_CUPM(to_host, B, destroy, MatDestroy_SeqDense, Destroy);
887   }
888   PetscFunctionReturn(PETSC_SUCCESS);
889 }
890 
891 // ==========================================================================================
892 // MatDense_Seq_CUPM - Public API
893 // ==========================================================================================
894 
895 template <device::cupm::DeviceType T>
896 inline constexpr MatType MatDense_Seq_CUPM<T>::MATIMPLCUPM_() noexcept
897 {
898   return MATSEQDENSECUPM();
899 }
900 
901 template <device::cupm::DeviceType T>
902 inline constexpr typename MatDense_Seq_CUPM<T>::Mat_SeqDenseCUPM *MatDense_Seq_CUPM<T>::MatCUPMCast(Mat m) noexcept
903 {
904   return static_cast<Mat_SeqDenseCUPM *>(m->spptr);
905 }
906 
907 template <device::cupm::DeviceType T>
908 inline constexpr Mat_SeqDense *MatDense_Seq_CUPM<T>::MatIMPLCast_(Mat m) noexcept
909 {
910   return static_cast<Mat_SeqDense *>(m->data);
911 }
912 
913 template <device::cupm::DeviceType T>
914 inline constexpr const char *MatDense_Seq_CUPM<T>::MatConvert_seqdensecupm_seqdense_C() noexcept
915 {
916   return T == device::cupm::DeviceType::CUDA ? "MatConvert_seqdensecuda_seqdense_C" : "MatConvert_seqdensehip_seqdense_C";
917 }
918 
919 template <device::cupm::DeviceType T>
920 inline constexpr const char *MatDense_Seq_CUPM<T>::MatProductSetFromOptions_seqaij_seqdensecupm_C() noexcept
921 {
922   return T == device::cupm::DeviceType::CUDA ? "MatProductSetFromOptions_seqaij_seqdensecuda_C" : "MatProductSetFromOptions_seqaij_seqdensehip_C";
923 }
924 
925 // ==========================================================================================
926 
927 // MatCreate_SeqDenseCUPM()
928 template <device::cupm::DeviceType T>
929 inline PetscErrorCode MatDense_Seq_CUPM<T>::Create(Mat A) noexcept
930 {
931   PetscFunctionBegin;
932   PetscCall(PetscDeviceInitialize(PETSC_DEVICE_CUPM()));
933   PetscCall(MatCreate_SeqDense(A));
934   PetscCall(Convert_SeqDense_SeqDenseCUPM(A, MATSEQDENSECUPM(), MAT_INPLACE_MATRIX, &A));
935   PetscFunctionReturn(PETSC_SUCCESS);
936 }
937 
938 template <device::cupm::DeviceType T>
939 inline PetscErrorCode MatDense_Seq_CUPM<T>::Destroy(Mat A) noexcept
940 {
941   PetscFunctionBegin;
942   // prevent copying back data if we own the data pointer
943   if (!MatIMPLCast(A)->user_alloc) A->offloadmask = PETSC_OFFLOAD_CPU;
944   PetscCall(Convert_SeqDenseCUPM_SeqDense(A, MATSEQDENSE, MAT_INPLACE_MATRIX, &A));
945   PetscCall(MatDestroy_SeqDense(A));
946   PetscFunctionReturn(PETSC_SUCCESS);
947 }
948 
949 // obj->ops->setup()
950 template <device::cupm::DeviceType T>
951 inline PetscErrorCode MatDense_Seq_CUPM<T>::SetUp(Mat A) noexcept
952 {
953   PetscFunctionBegin;
954   PetscCall(PetscLayoutSetUp(A->rmap));
955   PetscCall(PetscLayoutSetUp(A->cmap));
956   if (!A->preallocated) {
957     PetscDeviceContext dctx;
958 
959     PetscCall(GetHandles_(&dctx));
960     PetscCall(SetPreallocation(A, dctx, nullptr));
961   }
962   PetscFunctionReturn(PETSC_SUCCESS);
963 }
964 
965 template <device::cupm::DeviceType T>
966 inline PetscErrorCode MatDense_Seq_CUPM<T>::Reset(Mat A) noexcept
967 {
968   PetscFunctionBegin;
969   if (const auto mcu = MatCUPMCast(A)) {
970     cupmStream_t stream;
971 
972     PetscCheck(!mcu->unplacedarray, PETSC_COMM_SELF, PETSC_ERR_ORDER, "MatDense%sResetArray() must be called first", cupmNAME());
973     PetscCall(GetHandles_(&stream));
974     if (!mcu->d_user_alloc) PetscCallCUPM(cupmFreeAsync(mcu->d_v, stream));
975     PetscCallCUPM(cupmFreeAsync(mcu->d_fact_tau, stream));
976     PetscCallCUPM(cupmFreeAsync(mcu->d_fact_ipiv, stream));
977     PetscCallCUPM(cupmFreeAsync(mcu->d_fact_info, stream));
978     PetscCallCUPM(cupmFreeAsync(mcu->d_fact_work, stream));
979     PetscCall(VecDestroy(&mcu->workvec));
980     PetscCall(PetscFree(A->spptr /* mcu */));
981   }
982   PetscFunctionReturn(PETSC_SUCCESS);
983 }
984 
985 // ==========================================================================================
986 
987 template <device::cupm::DeviceType T>
988 inline PetscErrorCode MatDense_Seq_CUPM<T>::BindToCPU(Mat A, PetscBool to_host) noexcept
989 {
990   const auto mimpl = MatIMPLCast(A);
991   const auto pobj  = PetscObjectCast(A);
992 
993   PetscFunctionBegin;
994   PetscCheck(!mimpl->vecinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreColumnVec() first");
995   PetscCheck(!mimpl->matinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreSubMatrix() first");
996   A->boundtocpu = to_host;
997   PetscCall(PetscStrFreeAllocpy(to_host ? PETSCRANDER48 : PETSCDEVICERAND(), &A->defaultrandtype));
998   if (to_host) {
999     PetscDeviceContext dctx;
1000 
1001     // make sure we have an up-to-date copy on the CPU
1002     PetscCall(GetHandles_(&dctx));
1003     PetscCall(DeviceToHost_(A, dctx));
1004   } else {
1005     PetscBool iscupm;
1006 
1007     if (auto &cvec = mimpl->cvec) {
1008       PetscCall(PetscObjectTypeCompare(PetscObjectCast(cvec), VecSeq_CUPM::VECSEQCUPM(), &iscupm));
1009       if (!iscupm) PetscCall(VecDestroy(&cvec));
1010     }
1011     if (auto &cmat = mimpl->cmat) {
1012       PetscCall(PetscObjectTypeCompare(PetscObjectCast(cmat), MATSEQDENSECUPM(), &iscupm));
1013       if (!iscupm) PetscCall(MatDestroy(&cmat));
1014     }
1015   }
1016 
1017   // ============================================================
1018   // Composed ops
1019   // ============================================================
1020   MatComposeOp_CUPM(to_host, pobj, "MatDenseGetArray_C", MatDenseGetArray_SeqDense, GetArrayC_<PETSC_MEMTYPE_HOST, PETSC_MEMORY_ACCESS_READ_WRITE>);
1021   MatComposeOp_CUPM(to_host, pobj, "MatDenseGetArrayRead_C", MatDenseGetArray_SeqDense, GetArrayC_<PETSC_MEMTYPE_HOST, PETSC_MEMORY_ACCESS_READ>);
1022   MatComposeOp_CUPM(to_host, pobj, "MatDenseGetArrayWrite_C", MatDenseGetArray_SeqDense, GetArrayC_<PETSC_MEMTYPE_HOST, PETSC_MEMORY_ACCESS_WRITE>);
1023   MatComposeOp_CUPM(to_host, pobj, "MatDenseGetArrayAndMemType_C", nullptr, GetArrayAndMemTypeC_<PETSC_MEMORY_ACCESS_READ_WRITE>);
1024   MatComposeOp_CUPM(to_host, pobj, "MatDenseRestoreArrayAndMemType_C", nullptr, RestoreArrayAndMemTypeC_<PETSC_MEMORY_ACCESS_READ_WRITE>);
1025   MatComposeOp_CUPM(to_host, pobj, "MatDenseGetArrayReadAndMemType_C", nullptr, GetArrayAndMemTypeC_<PETSC_MEMORY_ACCESS_READ>);
1026   MatComposeOp_CUPM(to_host, pobj, "MatDenseRestoreArrayReadAndMemType_C", nullptr, RestoreArrayAndMemTypeC_<PETSC_MEMORY_ACCESS_READ>);
1027   MatComposeOp_CUPM(to_host, pobj, "MatDenseGetArrayWriteAndMemType_C", nullptr, GetArrayAndMemTypeC_<PETSC_MEMORY_ACCESS_WRITE>);
1028   MatComposeOp_CUPM(to_host, pobj, "MatDenseRestoreArrayWriteAndMemType_C", nullptr, RestoreArrayAndMemTypeC_<PETSC_MEMORY_ACCESS_WRITE>);
1029   MatComposeOp_CUPM(to_host, pobj, "MatDenseGetColumnVec_C", MatDenseGetColumnVec_SeqDense, GetColumnVec<PETSC_MEMORY_ACCESS_READ_WRITE>);
1030   MatComposeOp_CUPM(to_host, pobj, "MatDenseRestoreColumnVec_C", MatDenseRestoreColumnVec_SeqDense, RestoreColumnVec<PETSC_MEMORY_ACCESS_READ_WRITE>);
1031   MatComposeOp_CUPM(to_host, pobj, "MatDenseGetColumnVecRead_C", MatDenseGetColumnVecRead_SeqDense, GetColumnVec<PETSC_MEMORY_ACCESS_READ>);
1032   MatComposeOp_CUPM(to_host, pobj, "MatDenseRestoreColumnVecRead_C", MatDenseRestoreColumnVecRead_SeqDense, RestoreColumnVec<PETSC_MEMORY_ACCESS_READ>);
1033   MatComposeOp_CUPM(to_host, pobj, "MatDenseGetColumnVecWrite_C", MatDenseGetColumnVecWrite_SeqDense, GetColumnVec<PETSC_MEMORY_ACCESS_WRITE>);
1034   MatComposeOp_CUPM(to_host, pobj, "MatDenseRestoreColumnVecWrite_C", MatDenseRestoreColumnVecWrite_SeqDense, RestoreColumnVec<PETSC_MEMORY_ACCESS_WRITE>);
1035   MatComposeOp_CUPM(to_host, pobj, "MatDenseGetSubMatrix_C", MatDenseGetSubMatrix_SeqDense, GetSubMatrix);
1036   MatComposeOp_CUPM(to_host, pobj, "MatDenseRestoreSubMatrix_C", MatDenseRestoreSubMatrix_SeqDense, RestoreSubMatrix);
1037   MatComposeOp_CUPM(to_host, pobj, "MatQRFactor_C", MatQRFactor_SeqDense, SolveQR::Factor);
1038   // always the same
1039   PetscCall(PetscObjectComposeFunction(pobj, "MatDenseSetLDA_C", MatDenseSetLDA_SeqDense));
1040 
1041   // ============================================================
1042   // Function pointer ops
1043   // ============================================================
1044   MatSetOp_CUPM(to_host, A, duplicate, MatDuplicate_SeqDense, Duplicate);
1045   MatSetOp_CUPM(to_host, A, mult, MatMult_SeqDense, [](Mat A, Vec xx, Vec yy) { return MatMultAdd_Dispatch_</* transpose */ false, /* hermitian */ false>(A, xx, nullptr, yy); });
1046   MatSetOp_CUPM(to_host, A, multtranspose, MatMultTranspose_SeqDense, [](Mat A, Vec xx, Vec yy) { return MatMultAdd_Dispatch_</* transpose */ true, /* hermitian */ false>(A, xx, nullptr, yy); });
1047   MatSetOp_CUPM(to_host, A, multhermitiantranspose, MatMultTranspose_SeqDense, [](Mat A, Vec xx, Vec yy) { return MatMultAdd_Dispatch_</* transpose */ true, /* hermitian */ true>(A, xx, nullptr, yy); });
1048   MatSetOp_CUPM(to_host, A, multadd, MatMultAdd_SeqDense, MatMultAdd_Dispatch_</* transpose */ false, /* hermitian */ false>);
1049   MatSetOp_CUPM(to_host, A, multtransposeadd, MatMultTransposeAdd_SeqDense, MatMultAdd_Dispatch_</* transpose */ true, /* hermitian */ false>);
1050   MatSetOp_CUPM(to_host, A, multhermitiantransposeadd, MatMultHermitianTransposeAdd_SeqDense, MatMultAdd_Dispatch_</* transpose */ true, /* hermitian */ true>);
1051   MatSetOp_CUPM(to_host, A, matmultnumeric, MatMatMultNumeric_SeqDense_SeqDense, MatMatMult_Numeric_Dispatch</* transpose_A */ false, /* transpose_B */ false>);
1052   MatSetOp_CUPM(to_host, A, mattransposemultnumeric, MatMatTransposeMultNumeric_SeqDense_SeqDense, MatMatMult_Numeric_Dispatch</* transpose_A */ false, /* transpose_B */ true>);
1053   MatSetOp_CUPM(to_host, A, transposematmultnumeric, MatTransposeMatMultNumeric_SeqDense_SeqDense, MatMatMult_Numeric_Dispatch</* transpose_A */ true, /* transpose_B */ false>);
1054   MatSetOp_CUPM(to_host, A, axpy, MatAXPY_SeqDense, AXPY);
1055   MatSetOp_CUPM(to_host, A, choleskyfactor, MatCholeskyFactor_SeqDense, SolveCholesky::Factor);
1056   MatSetOp_CUPM(to_host, A, lufactor, MatLUFactor_SeqDense, SolveLU::Factor);
1057   MatSetOp_CUPM(to_host, A, getcolumnvector, MatGetColumnVector_SeqDense, GetColumnVector);
1058   MatSetOp_CUPM(to_host, A, scale, MatScale_SeqDense, Scale);
1059   MatSetOp_CUPM(to_host, A, shift, MatShift_SeqDense, Shift);
1060   MatSetOp_CUPM(to_host, A, copy, MatCopy_SeqDense, Copy);
1061   MatSetOp_CUPM(to_host, A, zeroentries, MatZeroEntries_SeqDense, ZeroEntries);
1062   MatSetOp_CUPM(to_host, A, setup, MatSetUp_SeqDense, SetUp);
1063   MatSetOp_CUPM(to_host, A, setrandom, MatSetRandom_SeqDense, SetRandom);
1064   MatSetOp_CUPM(to_host, A, getdiagonal, MatGetDiagonal_SeqDense, GetDiagonal);
1065   // seemingly always the same
1066   A->ops->productsetfromoptions = MatProductSetFromOptions_SeqDense;
1067 
1068   if (const auto cmat = mimpl->cmat) PetscCall(MatBindToCPU(cmat, to_host));
1069   PetscFunctionReturn(PETSC_SUCCESS);
1070 }
1071 
1072 template <device::cupm::DeviceType T>
1073 inline PetscErrorCode MatDense_Seq_CUPM<T>::Convert_SeqDenseCUPM_SeqDense(Mat M, MatType type, MatReuse reuse, Mat *newmat) noexcept
1074 {
1075   PetscFunctionBegin;
1076   PetscCall(Convert_Dispatch_</* to host */ true>(M, type, reuse, newmat));
1077   PetscFunctionReturn(PETSC_SUCCESS);
1078 }
1079 
1080 template <device::cupm::DeviceType T>
1081 inline PetscErrorCode MatDense_Seq_CUPM<T>::Convert_SeqDense_SeqDenseCUPM(Mat M, MatType type, MatReuse reuse, Mat *newmat) noexcept
1082 {
1083   PetscFunctionBegin;
1084   PetscCall(Convert_Dispatch_</* to host */ false>(M, type, reuse, newmat));
1085   PetscFunctionReturn(PETSC_SUCCESS);
1086 }
1087 
1088 // ==========================================================================================
1089 
1090 template <device::cupm::DeviceType T>
1091 template <PetscMemType mtype, PetscMemoryAccessMode access>
1092 inline PetscErrorCode MatDense_Seq_CUPM<T>::GetArray(Mat m, PetscScalar **array, PetscDeviceContext dctx) noexcept
1093 {
1094   constexpr auto hostmem     = PetscMemTypeHost(mtype);
1095   constexpr auto read_access = PetscMemoryAccessRead(access);
1096 
1097   PetscFunctionBegin;
1098   static_assert((mtype == PETSC_MEMTYPE_HOST) || (mtype == PETSC_MEMTYPE_DEVICE), "");
1099   PetscCall(PetscDeviceContextGetOptionalNullContext_Internal(&dctx));
1100   if (hostmem) {
1101     if (read_access) {
1102       PetscCall(DeviceToHost_(m, dctx));
1103     } else if (!MatIMPLCast(m)->v) {
1104       // MatCreateSeqDenseCUPM may not allocate CPU memory. Allocate if needed
1105       PetscCall(MatSeqDenseSetPreallocation(m, nullptr));
1106     }
1107     *array = MatIMPLCast(m)->v;
1108   } else {
1109     if (read_access) {
1110       PetscCall(HostToDevice_(m, dctx));
1111     } else if (!MatCUPMCast(m)->d_v) {
1112       // write-only
1113       PetscCall(SetPreallocation(m, dctx, nullptr));
1114     }
1115     *array = MatCUPMCast(m)->d_v;
1116   }
1117   if (PetscMemoryAccessWrite(access)) {
1118     m->offloadmask = hostmem ? PETSC_OFFLOAD_CPU : PETSC_OFFLOAD_GPU;
1119     PetscCall(PetscObjectStateIncrease(PetscObjectCast(m)));
1120   }
1121   PetscFunctionReturn(PETSC_SUCCESS);
1122 }
1123 
1124 template <device::cupm::DeviceType T>
1125 template <PetscMemType mtype, PetscMemoryAccessMode access>
1126 inline PetscErrorCode MatDense_Seq_CUPM<T>::RestoreArray(Mat m, PetscScalar **array, PetscDeviceContext) noexcept
1127 {
1128   PetscFunctionBegin;
1129   static_assert((mtype == PETSC_MEMTYPE_HOST) || (mtype == PETSC_MEMTYPE_DEVICE), "");
1130   if (PetscMemoryAccessWrite(access)) {
1131     // WRITE or READ_WRITE
1132     m->offloadmask = PetscMemTypeHost(mtype) ? PETSC_OFFLOAD_CPU : PETSC_OFFLOAD_GPU;
1133     PetscCall(PetscObjectStateIncrease(PetscObjectCast(m)));
1134   }
1135   if (array) {
1136     PetscCall(CheckPointerMatchesMemType_(*array, mtype));
1137     *array = nullptr;
1138   }
1139   PetscFunctionReturn(PETSC_SUCCESS);
1140 }
1141 
1142 template <device::cupm::DeviceType T>
1143 template <PetscMemoryAccessMode access>
1144 inline PetscErrorCode MatDense_Seq_CUPM<T>::GetArrayAndMemType(Mat m, PetscScalar **array, PetscMemType *mtype, PetscDeviceContext dctx) noexcept
1145 {
1146   PetscFunctionBegin;
1147   PetscCall(GetArray<PETSC_MEMTYPE_DEVICE, access>(m, array, dctx));
1148   if (mtype) *mtype = PETSC_MEMTYPE_CUPM();
1149   PetscFunctionReturn(PETSC_SUCCESS);
1150 }
1151 
1152 template <device::cupm::DeviceType T>
1153 template <PetscMemoryAccessMode access>
1154 inline PetscErrorCode MatDense_Seq_CUPM<T>::RestoreArrayAndMemType(Mat m, PetscScalar **array, PetscDeviceContext dctx) noexcept
1155 {
1156   PetscFunctionBegin;
1157   PetscCall(RestoreArray<PETSC_MEMTYPE_DEVICE, access>(m, array, dctx));
1158   PetscFunctionReturn(PETSC_SUCCESS);
1159 }
1160 
1161 // ==========================================================================================
1162 
1163 template <device::cupm::DeviceType T>
1164 inline PetscErrorCode MatDense_Seq_CUPM<T>::PlaceArray(Mat A, const PetscScalar *array) noexcept
1165 {
1166   const auto mimpl = MatIMPLCast(A);
1167   const auto mcu   = MatCUPMCast(A);
1168 
1169   PetscFunctionBegin;
1170   PetscCheck(!mimpl->vecinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreColumnVec() first");
1171   PetscCheck(!mimpl->matinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreSubMatrix() first");
1172   PetscCheck(!mcu->unplacedarray, PETSC_COMM_SELF, PETSC_ERR_ORDER, "MatDense%sResetArray() must be called first", cupmNAME());
1173   if (mimpl->v) {
1174     PetscDeviceContext dctx;
1175 
1176     PetscCall(GetHandles_(&dctx));
1177     PetscCall(HostToDevice_(A, dctx));
1178   }
1179   mcu->unplacedarray         = util::exchange(mcu->d_v, const_cast<PetscScalar *>(array));
1180   mcu->d_unplaced_user_alloc = util::exchange(mcu->d_user_alloc, PETSC_TRUE);
1181   PetscFunctionReturn(PETSC_SUCCESS);
1182 }
1183 
1184 template <device::cupm::DeviceType T>
1185 inline PetscErrorCode MatDense_Seq_CUPM<T>::ReplaceArray(Mat A, const PetscScalar *array) noexcept
1186 {
1187   const auto mimpl = MatIMPLCast(A);
1188   const auto mcu   = MatCUPMCast(A);
1189 
1190   PetscFunctionBegin;
1191   PetscCheck(!mimpl->vecinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreColumnVec() first");
1192   PetscCheck(!mimpl->matinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreSubMatrix() first");
1193   PetscCheck(!mcu->unplacedarray, PETSC_COMM_SELF, PETSC_ERR_ORDER, "MatDense%sResetArray() must be called first", cupmNAME());
1194   if (!mcu->d_user_alloc) {
1195     cupmStream_t stream;
1196 
1197     PetscCall(GetHandles_(&stream));
1198     PetscCallCUPM(cupmFreeAsync(mcu->d_v, stream));
1199   }
1200   mcu->d_v          = const_cast<PetscScalar *>(array);
1201   mcu->d_user_alloc = PETSC_FALSE;
1202   PetscFunctionReturn(PETSC_SUCCESS);
1203 }
1204 
1205 template <device::cupm::DeviceType T>
1206 inline PetscErrorCode MatDense_Seq_CUPM<T>::ResetArray(Mat A) noexcept
1207 {
1208   const auto mimpl = MatIMPLCast(A);
1209   const auto mcu   = MatCUPMCast(A);
1210 
1211   PetscFunctionBegin;
1212   PetscCheck(!mimpl->vecinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreColumnVec() first");
1213   PetscCheck(!mimpl->matinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreSubMatrix() first");
1214   if (mimpl->v) {
1215     PetscDeviceContext dctx;
1216 
1217     PetscCall(GetHandles_(&dctx));
1218     PetscCall(HostToDevice_(A, dctx));
1219   }
1220   mcu->d_v          = util::exchange(mcu->unplacedarray, nullptr);
1221   mcu->d_user_alloc = mcu->d_unplaced_user_alloc;
1222   PetscFunctionReturn(PETSC_SUCCESS);
1223 }
1224 
1225 // ==========================================================================================
1226 
1227 template <device::cupm::DeviceType T>
1228 template <bool transpose_A, bool transpose_B>
1229 inline PetscErrorCode MatDense_Seq_CUPM<T>::MatMatMult_Numeric_Dispatch(Mat A, Mat B, Mat C) noexcept
1230 {
1231   cupmBlasInt_t      m, n, k;
1232   PetscBool          Aiscupm, Biscupm;
1233   PetscDeviceContext dctx;
1234   cupmBlasHandle_t   handle;
1235 
1236   PetscFunctionBegin;
1237   PetscCall(PetscCUPMBlasIntCast(C->rmap->n, &m));
1238   PetscCall(PetscCUPMBlasIntCast(C->cmap->n, &n));
1239   PetscCall(PetscCUPMBlasIntCast(transpose_A ? A->rmap->n : A->cmap->n, &k));
1240   if (!m || !n || !k) PetscFunctionReturn(PETSC_SUCCESS);
1241 
1242   // we may end up with SEQDENSE as one of the arguments
1243   // REVIEW ME: how? and why is it not B and C????????
1244   PetscCall(PetscObjectTypeCompare(PetscObjectCast(A), MATSEQDENSECUPM(), &Aiscupm));
1245   PetscCall(PetscObjectTypeCompare(PetscObjectCast(B), MATSEQDENSECUPM(), &Biscupm));
1246   if (!Aiscupm) PetscCall(MatConvert(A, MATSEQDENSECUPM(), MAT_INPLACE_MATRIX, &A));
1247   if (!Biscupm) PetscCall(MatConvert(B, MATSEQDENSECUPM(), MAT_INPLACE_MATRIX, &B));
1248   PetscCall(PetscInfo(C, "Matrix-Matrix product %" PetscBLASInt_FMT " x %" PetscBLASInt_FMT " x %" PetscBLASInt_FMT " on backend\n", m, k, n));
1249   PetscCall(GetHandles_(&dctx, &handle));
1250 
1251   PetscCall(PetscLogGpuTimeBegin());
1252   {
1253     const auto one  = cupmScalarCast(1.0);
1254     const auto zero = cupmScalarCast(0.0);
1255     const auto da   = DeviceArrayRead(dctx, A);
1256     const auto db   = DeviceArrayRead(dctx, B);
1257     const auto dc   = DeviceArrayWrite(dctx, C);
1258     PetscInt   alda, blda, clda;
1259 
1260     PetscCall(MatDenseGetLDA(A, &alda));
1261     PetscCall(MatDenseGetLDA(B, &blda));
1262     PetscCall(MatDenseGetLDA(C, &clda));
1263     PetscCallCUPMBLAS(cupmBlasXgemm(handle, transpose_A ? CUPMBLAS_OP_T : CUPMBLAS_OP_N, transpose_B ? CUPMBLAS_OP_T : CUPMBLAS_OP_N, m, n, k, &one, da.cupmdata(), alda, db.cupmdata(), blda, &zero, dc.cupmdata(), clda));
1264   }
1265   PetscCall(PetscLogGpuTimeEnd());
1266 
1267   PetscCall(PetscLogGpuFlops(1.0 * m * n * k + 1.0 * m * n * (k - 1)));
1268   if (!Aiscupm) PetscCall(MatConvert(A, MATSEQDENSE, MAT_INPLACE_MATRIX, &A));
1269   if (!Biscupm) PetscCall(MatConvert(B, MATSEQDENSE, MAT_INPLACE_MATRIX, &B));
1270   PetscFunctionReturn(PETSC_SUCCESS);
1271 }
1272 
1273 template <device::cupm::DeviceType T>
1274 inline PetscErrorCode MatDense_Seq_CUPM<T>::Copy(Mat A, Mat B, MatStructure str) noexcept
1275 {
1276   const auto m = A->rmap->n;
1277   const auto n = A->cmap->n;
1278 
1279   PetscFunctionBegin;
1280   PetscAssert(m == B->rmap->n && n == B->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "size(B) != size(A)");
1281   // The two matrices must have the same copy implementation to be eligible for fast copy
1282   if (A->ops->copy == B->ops->copy) {
1283     PetscDeviceContext dctx;
1284     cupmStream_t       stream;
1285 
1286     PetscCall(GetHandles_(&dctx, &stream));
1287     PetscCall(PetscLogGpuTimeBegin());
1288     {
1289       const auto va = DeviceArrayRead(dctx, A);
1290       const auto vb = DeviceArrayWrite(dctx, B);
1291       // order is important, DeviceArrayRead/Write() might call SetPreallocation() which sets
1292       // lda!
1293       const auto lda_a = MatIMPLCast(A)->lda;
1294       const auto lda_b = MatIMPLCast(B)->lda;
1295 
1296       if (lda_a > m || lda_b > m) {
1297         PetscAssert(lda_b > 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "B lda (%" PetscBLASInt_FMT ") must be > 0 at this point, this indicates Mat%sSetPreallocation() was not called when it should have been!", lda_b, cupmNAME());
1298         PetscAssert(lda_a > 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "A lda (%" PetscBLASInt_FMT ") must be > 0 at this point, this indicates Mat%sSetPreallocation() was not called when it should have been!", lda_a, cupmNAME());
1299         PetscCall(PetscCUPMMemcpy2DAsync(vb.data(), lda_b, va.data(), lda_a, m, n, cupmMemcpyDeviceToDevice, stream));
1300       } else {
1301         PetscCall(PetscCUPMMemcpyAsync(vb.data(), va.data(), m * n, cupmMemcpyDeviceToDevice, stream));
1302       }
1303     }
1304     PetscCall(PetscLogGpuTimeEnd());
1305   } else {
1306     PetscCall(MatCopy_Basic(A, B, str));
1307   }
1308   PetscFunctionReturn(PETSC_SUCCESS);
1309 }
1310 
1311 template <device::cupm::DeviceType T>
1312 inline PetscErrorCode MatDense_Seq_CUPM<T>::ZeroEntries(Mat m) noexcept
1313 {
1314   PetscDeviceContext dctx;
1315   cupmStream_t       stream;
1316 
1317   PetscFunctionBegin;
1318   PetscCall(GetHandles_(&dctx, &stream));
1319   PetscCall(PetscLogGpuTimeBegin());
1320   {
1321     const auto va  = DeviceArrayWrite(dctx, m);
1322     const auto lda = MatIMPLCast(m)->lda;
1323     const auto ma  = m->rmap->n;
1324     const auto na  = m->cmap->n;
1325 
1326     if (lda > ma) {
1327       PetscCall(PetscCUPMMemset2DAsync(va.data(), lda, 0, ma, na, stream));
1328     } else {
1329       PetscCall(PetscCUPMMemsetAsync(va.data(), 0, ma * na, stream));
1330     }
1331   }
1332   PetscCall(PetscLogGpuTimeEnd());
1333   PetscFunctionReturn(PETSC_SUCCESS);
1334 }
1335 
1336 namespace detail
1337 {
1338 
1339 // ==========================================================================================
1340 // SubMatIndexFunctor
1341 //
1342 // Iterator which permutes a linear index range into matrix indices for am nrows x ncols
1343 // submat with leading dimension lda. Essentially SubMatIndexFunctor(i) returns the index for
1344 // the i'th sequential entry in the matrix.
1345 // ==========================================================================================
1346 template <typename T>
1347 struct SubMatIndexFunctor {
1348   PETSC_HOSTDEVICE_INLINE_DECL T operator()(T x) const noexcept { return ((x / nrows) * lda) + (x % nrows); }
1349 
1350   PetscInt nrows;
1351   PetscInt ncols;
1352   PetscInt lda;
1353 };
1354 
1355 template <typename Iterator>
1356 struct SubMatrixIterator : MatrixIteratorBase<Iterator, SubMatIndexFunctor<typename thrust::iterator_difference<Iterator>::type>> {
1357   using base_type = MatrixIteratorBase<Iterator, SubMatIndexFunctor<typename thrust::iterator_difference<Iterator>::type>>;
1358 
1359   using iterator = typename base_type::iterator;
1360 
1361   constexpr SubMatrixIterator(Iterator first, Iterator last, PetscInt nrows, PetscInt ncols, PetscInt lda) noexcept :
1362     base_type{
1363       std::move(first), std::move(last), {nrows, ncols, lda}
1364   }
1365   {
1366   }
1367 
1368   PETSC_NODISCARD iterator end() const noexcept { return this->begin() + (this->func.nrows * this->func.ncols); }
1369 };
1370 
1371 namespace
1372 {
1373 
1374 template <typename T>
1375 PETSC_NODISCARD inline SubMatrixIterator<typename thrust::device_vector<T>::iterator> make_submat_iterator(PetscInt rstart, PetscInt rend, PetscInt cstart, PetscInt cend, PetscInt lda, T *ptr) noexcept
1376 {
1377   const auto nrows = rend - rstart;
1378   const auto ncols = cend - cstart;
1379   const auto dptr  = thrust::device_pointer_cast(ptr);
1380 
1381   return {dptr + (rstart * lda) + cstart, dptr + ((rstart + nrows) * lda) + cstart, nrows, ncols, lda};
1382 }
1383 
1384 } // namespace
1385 
1386 } // namespace detail
1387 
1388 template <device::cupm::DeviceType T>
1389 inline PetscErrorCode MatDense_Seq_CUPM<T>::Scale(Mat A, PetscScalar alpha) noexcept
1390 {
1391   const auto         m = A->rmap->n;
1392   const auto         n = A->cmap->n;
1393   const auto         N = m * n;
1394   PetscDeviceContext dctx;
1395 
1396   PetscFunctionBegin;
1397   PetscCall(PetscInfo(A, "Performing Scale %" PetscInt_FMT " x %" PetscInt_FMT " on backend\n", m, n));
1398   PetscCall(GetHandles_(&dctx));
1399   {
1400     const auto da  = DeviceArrayReadWrite(dctx, A);
1401     const auto lda = MatIMPLCast(A)->lda;
1402 
1403     if (lda > m) {
1404       cupmStream_t stream;
1405 
1406       PetscCall(GetHandlesFrom_(dctx, &stream));
1407       // clang-format off
1408       PetscCallThrust(
1409         const auto sub_mat = detail::make_submat_iterator(0, m, 0, n, lda, da.data());
1410 
1411         THRUST_CALL(
1412           thrust::transform,
1413           stream,
1414           sub_mat.begin(), sub_mat.end(), sub_mat.begin(),
1415           device::cupm::functors::make_times_equals(alpha)
1416         )
1417       );
1418       // clang-format on
1419     } else {
1420       const auto       cu_alpha = cupmScalarCast(alpha);
1421       cupmBlasHandle_t handle;
1422 
1423       PetscCall(GetHandlesFrom_(dctx, &handle));
1424       PetscCall(PetscLogGpuTimeBegin());
1425       PetscCallCUPMBLAS(cupmBlasXscal(handle, N, &cu_alpha, da.cupmdata(), 1));
1426       PetscCall(PetscLogGpuTimeEnd());
1427     }
1428   }
1429   PetscCall(PetscLogGpuFlops(N));
1430   PetscFunctionReturn(PETSC_SUCCESS);
1431 }
1432 
1433 template <device::cupm::DeviceType T>
1434 inline PetscErrorCode MatDense_Seq_CUPM<T>::AXPY(Mat Y, PetscScalar alpha, Mat X, MatStructure) noexcept
1435 {
1436   const auto         m_x = X->rmap->n, m_y = Y->rmap->n;
1437   const auto         n_x = X->cmap->n, n_y = Y->cmap->n;
1438   const auto         N = m_x * n_x;
1439   PetscDeviceContext dctx;
1440 
1441   PetscFunctionBegin;
1442   if (!m_x || !n_x || alpha == (PetscScalar)0.0) PetscFunctionReturn(PETSC_SUCCESS);
1443   PetscCall(PetscInfo(Y, "Performing AXPY %" PetscInt_FMT " x %" PetscInt_FMT " on backend\n", m_y, n_y));
1444   PetscCall(GetHandles_(&dctx));
1445   {
1446     const auto dx    = DeviceArrayRead(dctx, X);
1447     const auto dy    = DeviceArrayReadWrite(dctx, Y);
1448     const auto lda_x = MatIMPLCast(X)->lda;
1449     const auto lda_y = MatIMPLCast(Y)->lda;
1450 
1451     if (lda_x > m_x || lda_y > m_x) {
1452       cupmStream_t stream;
1453 
1454       PetscCall(GetHandlesFrom_(dctx, &stream));
1455       // clang-format off
1456       PetscCallThrust(
1457         const auto sub_mat_y = detail::make_submat_iterator(0, m_y, 0, n_y, lda_y, dy.data());
1458         const auto sub_mat_x = detail::make_submat_iterator(0, m_x, 0, n_x, lda_x, dx.data());
1459 
1460         THRUST_CALL(
1461           thrust::transform,
1462           stream,
1463           sub_mat_x.begin(), sub_mat_x.end(), sub_mat_y.begin(), sub_mat_y.begin(),
1464           device::cupm::functors::make_axpy(alpha)
1465         );
1466       );
1467       // clang-format on
1468     } else {
1469       const auto       cu_alpha = cupmScalarCast(alpha);
1470       cupmBlasHandle_t handle;
1471 
1472       PetscCall(GetHandlesFrom_(dctx, &handle));
1473       PetscCall(PetscLogGpuTimeBegin());
1474       PetscCallCUPMBLAS(cupmBlasXaxpy(handle, N, &cu_alpha, dx.cupmdata(), 1, dy.cupmdata(), 1));
1475       PetscCall(PetscLogGpuTimeEnd());
1476     }
1477   }
1478   PetscCall(PetscLogGpuFlops(PetscMax(2 * N - 1, 0)));
1479   PetscFunctionReturn(PETSC_SUCCESS);
1480 }
1481 
1482 template <device::cupm::DeviceType T>
1483 inline PetscErrorCode MatDense_Seq_CUPM<T>::Duplicate(Mat A, MatDuplicateOption opt, Mat *B) noexcept
1484 {
1485   const auto         hopt = (opt == MAT_COPY_VALUES && A->offloadmask != PETSC_OFFLOAD_CPU) ? MAT_DO_NOT_COPY_VALUES : opt;
1486   PetscDeviceContext dctx;
1487 
1488   PetscFunctionBegin;
1489   PetscCall(GetHandles_(&dctx));
1490   // do not call SetPreallocation() yet, we call it afterwards??
1491   PetscCall(MatCreateSeqDenseCUPM<T>(PetscObjectComm(PetscObjectCast(A)), A->rmap->n, A->cmap->n, nullptr, B, dctx, /* preallocate */ false));
1492   PetscCall(MatDuplicateNoCreate_SeqDense(*B, A, hopt));
1493   if (opt == MAT_COPY_VALUES && hopt != MAT_COPY_VALUES) PetscCall(Copy(A, *B, SAME_NONZERO_PATTERN));
1494   // allocate memory if needed
1495   if (opt != MAT_COPY_VALUES && !MatCUPMCast(*B)->d_v) PetscCall(SetPreallocation(*B, dctx, nullptr));
1496   PetscFunctionReturn(PETSC_SUCCESS);
1497 }
1498 
1499 template <device::cupm::DeviceType T>
1500 inline PetscErrorCode MatDense_Seq_CUPM<T>::SetRandom(Mat A, PetscRandom rng) noexcept
1501 {
1502   PetscBool device;
1503 
1504   PetscFunctionBegin;
1505   PetscCall(PetscObjectTypeCompare(PetscObjectCast(rng), PETSCDEVICERAND(), &device));
1506   if (device) {
1507     const auto         m = A->rmap->n;
1508     const auto         n = A->cmap->n;
1509     PetscDeviceContext dctx;
1510 
1511     PetscCall(GetHandles_(&dctx));
1512     {
1513       const auto a = DeviceArrayWrite(dctx, A);
1514       PetscInt   lda;
1515 
1516       PetscCall(MatDenseGetLDA(A, &lda));
1517       if (lda > m) {
1518         for (PetscInt i = 0; i < n; i++) PetscCall(PetscRandomGetValues(rng, m, a.data() + i * lda));
1519       } else {
1520         PetscInt mn;
1521 
1522         PetscCall(PetscIntMultError(m, n, &mn));
1523         PetscCall(PetscRandomGetValues(rng, mn, a));
1524       }
1525     }
1526   } else {
1527     PetscCall(MatSetRandom_SeqDense(A, rng));
1528   }
1529   PetscFunctionReturn(PETSC_SUCCESS);
1530 }
1531 
1532 // ==========================================================================================
1533 
1534 template <device::cupm::DeviceType T>
1535 inline PetscErrorCode MatDense_Seq_CUPM<T>::GetColumnVector(Mat A, Vec v, PetscInt col) noexcept
1536 {
1537   const auto         offloadmask = A->offloadmask;
1538   const auto         n           = A->rmap->n;
1539   const auto         col_offset  = [&](const PetscScalar *ptr) { return ptr + col * MatIMPLCast(A)->lda; };
1540   PetscBool          viscupm;
1541   PetscDeviceContext dctx;
1542   cupmStream_t       stream;
1543 
1544   PetscFunctionBegin;
1545   PetscCall(PetscObjectTypeCompareAny(PetscObjectCast(v), &viscupm, VecSeq_CUPM::VECSEQCUPM(), VecSeq_CUPM::VECMPICUPM(), VecSeq_CUPM::VECCUPM(), ""));
1546   PetscCall(GetHandles_(&dctx, &stream));
1547   if (viscupm && !v->boundtocpu) {
1548     const auto x = VecSeq_CUPM::DeviceArrayWrite(dctx, v);
1549 
1550     // update device data
1551     if (PetscOffloadDevice(offloadmask)) {
1552       PetscCall(PetscCUPMMemcpyAsync(x.data(), col_offset(DeviceArrayRead(dctx, A)), n, cupmMemcpyDeviceToDevice, stream));
1553     } else {
1554       PetscCall(PetscCUPMMemcpyAsync(x.data(), col_offset(HostArrayRead(dctx, A)), n, cupmMemcpyHostToDevice, stream));
1555     }
1556   } else {
1557     PetscScalar *x;
1558 
1559     // update host data
1560     PetscCall(VecGetArrayWrite(v, &x));
1561     if (PetscOffloadUnallocated(offloadmask) || PetscOffloadHost(offloadmask)) {
1562       PetscCall(PetscArraycpy(x, col_offset(HostArrayRead(dctx, A)), n));
1563     } else if (PetscOffloadDevice(offloadmask)) {
1564       PetscCall(PetscCUPMMemcpyAsync(x, col_offset(DeviceArrayRead(dctx, A)), n, cupmMemcpyDeviceToHost, stream));
1565     }
1566     PetscCall(VecRestoreArrayWrite(v, &x));
1567   }
1568   PetscFunctionReturn(PETSC_SUCCESS);
1569 }
1570 
1571 template <device::cupm::DeviceType T>
1572 template <PetscMemoryAccessMode access>
1573 inline PetscErrorCode MatDense_Seq_CUPM<T>::GetColumnVec(Mat A, PetscInt col, Vec *v) noexcept
1574 {
1575   using namespace vec::cupm;
1576   const auto         mimpl = MatIMPLCast(A);
1577   PetscDeviceContext dctx;
1578 
1579   PetscFunctionBegin;
1580   PetscCheck(!mimpl->vecinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreColumnVec() first");
1581   PetscCheck(!mimpl->matinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreSubMatrix() first");
1582   mimpl->vecinuse = col + 1;
1583   if (!mimpl->cvec) PetscCall(MatDenseCreateColumnVec_Private(A, &mimpl->cvec));
1584   PetscCall(GetHandles_(&dctx));
1585   PetscCall(GetArray<PETSC_MEMTYPE_DEVICE, access>(A, const_cast<PetscScalar **>(&mimpl->ptrinuse), dctx));
1586   PetscCall(VecCUPMPlaceArrayAsync<T>(mimpl->cvec, mimpl->ptrinuse + static_cast<std::size_t>(col) * static_cast<std::size_t>(mimpl->lda)));
1587   if (access == PETSC_MEMORY_ACCESS_READ) PetscCall(VecLockReadPush(mimpl->cvec));
1588   *v = mimpl->cvec;
1589   PetscFunctionReturn(PETSC_SUCCESS);
1590 }
1591 
1592 template <device::cupm::DeviceType T>
1593 template <PetscMemoryAccessMode access>
1594 inline PetscErrorCode MatDense_Seq_CUPM<T>::RestoreColumnVec(Mat A, PetscInt, Vec *v) noexcept
1595 {
1596   using namespace vec::cupm;
1597   const auto         mimpl = MatIMPLCast(A);
1598   const auto         cvec  = mimpl->cvec;
1599   PetscDeviceContext dctx;
1600 
1601   PetscFunctionBegin;
1602   PetscCheck(mimpl->vecinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseGetColumnVec() first");
1603   PetscCheck(cvec, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Missing internal column vector");
1604   mimpl->vecinuse = 0;
1605   if (access == PETSC_MEMORY_ACCESS_READ) PetscCall(VecLockReadPop(cvec));
1606   PetscCall(VecCUPMResetArrayAsync<T>(cvec));
1607   PetscCall(GetHandles_(&dctx));
1608   PetscCall(RestoreArray<PETSC_MEMTYPE_DEVICE, access>(A, const_cast<PetscScalar **>(&mimpl->ptrinuse), dctx));
1609   if (v) *v = nullptr;
1610   PetscFunctionReturn(PETSC_SUCCESS);
1611 }
1612 
1613 // ==========================================================================================
1614 
1615 template <device::cupm::DeviceType T>
1616 inline PetscErrorCode MatDense_Seq_CUPM<T>::GetFactor(Mat A, MatFactorType ftype, Mat *fact_out) noexcept
1617 {
1618   Mat                fact = nullptr;
1619   PetscDeviceContext dctx;
1620 
1621   PetscFunctionBegin;
1622   PetscCall(GetHandles_(&dctx));
1623   PetscCall(MatCreateSeqDenseCUPM<T>(PetscObjectComm(PetscObjectCast(A)), A->rmap->n, A->cmap->n, nullptr, &fact, dctx, /* preallocate */ false));
1624   fact->factortype = ftype;
1625   switch (ftype) {
1626   case MAT_FACTOR_LU:
1627   case MAT_FACTOR_ILU: // fall-through
1628     fact->ops->lufactorsymbolic  = MatLUFactorSymbolic_SeqDense;
1629     fact->ops->ilufactorsymbolic = MatLUFactorSymbolic_SeqDense;
1630     break;
1631   case MAT_FACTOR_CHOLESKY:
1632   case MAT_FACTOR_ICC: // fall-through
1633     fact->ops->choleskyfactorsymbolic = MatCholeskyFactorSymbolic_SeqDense;
1634     break;
1635   case MAT_FACTOR_QR: {
1636     const auto pobj = PetscObjectCast(fact);
1637 
1638     PetscCall(PetscObjectComposeFunction(pobj, "MatQRFactor_C", MatQRFactor_SeqDense));
1639     PetscCall(PetscObjectComposeFunction(pobj, "MatQRFactorSymbolic_C", MatQRFactorSymbolic_SeqDense));
1640   } break;
1641   case MAT_FACTOR_NONE:
1642   case MAT_FACTOR_ILUDT:     // fall-through
1643   case MAT_FACTOR_NUM_TYPES: // fall-through
1644     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "MatFactorType %s not supported", MatFactorTypes[ftype]);
1645   }
1646   PetscCall(PetscStrFreeAllocpy(MATSOLVERCUPM(), &fact->solvertype));
1647   PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, const_cast<char **>(fact->preferredordering) + MAT_FACTOR_LU));
1648   PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, const_cast<char **>(fact->preferredordering) + MAT_FACTOR_ILU));
1649   PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, const_cast<char **>(fact->preferredordering) + MAT_FACTOR_CHOLESKY));
1650   PetscCall(PetscStrallocpy(MATORDERINGEXTERNAL, const_cast<char **>(fact->preferredordering) + MAT_FACTOR_ICC));
1651   *fact_out = fact;
1652   PetscFunctionReturn(PETSC_SUCCESS);
1653 }
1654 
1655 template <device::cupm::DeviceType T>
1656 inline PetscErrorCode MatDense_Seq_CUPM<T>::InvertFactors(Mat A) noexcept
1657 {
1658   const auto         mimpl = MatIMPLCast(A);
1659   const auto         mcu   = MatCUPMCast(A);
1660   const auto         n     = static_cast<cupmBlasInt_t>(A->cmap->n);
1661   cupmSolverHandle_t handle;
1662   PetscDeviceContext dctx;
1663   cupmStream_t       stream;
1664 
1665   PetscFunctionBegin;
1666 #if PetscDefined(HAVE_CUDA) && PetscDefined(USING_NVCC)
1667   // HIP appears to have this by default??
1668   PetscCheck(PETSC_PKG_CUDA_VERSION_GE(10, 1, 0), PETSC_COMM_SELF, PETSC_ERR_SUP, "Upgrade to CUDA version 10.1.0 or higher");
1669 #endif
1670   if (!n || !A->rmap->n) PetscFunctionReturn(PETSC_SUCCESS);
1671   PetscCheck(A->factortype == MAT_FACTOR_CHOLESKY, PETSC_COMM_SELF, PETSC_ERR_LIB, "Factor type %s not implemented", MatFactorTypes[A->factortype]);
1672   // spd
1673   PetscCheck(!mcu->d_fact_ipiv, PETSC_COMM_SELF, PETSC_ERR_LIB, "%sDnsytri not implemented", cupmSolverName());
1674 
1675   PetscCall(GetHandles_(&dctx, &handle, &stream));
1676   {
1677     const auto    da  = DeviceArrayReadWrite(dctx, A);
1678     const auto    lda = static_cast<cupmBlasInt_t>(mimpl->lda);
1679     cupmBlasInt_t il;
1680 
1681     PetscCallCUPMSOLVER(cupmSolverXpotri_bufferSize(handle, CUPMSOLVER_FILL_MODE_LOWER, n, da.cupmdata(), lda, &il));
1682     if (il > mcu->d_fact_lwork) {
1683       mcu->d_fact_lwork = il;
1684       PetscCallCUPM(cupmFreeAsync(mcu->d_fact_work, stream));
1685       PetscCall(PetscCUPMMallocAsync(&mcu->d_fact_work, il, stream));
1686     }
1687     PetscCall(PetscLogGpuTimeBegin());
1688     PetscCallCUPMSOLVER(cupmSolverXpotri(handle, CUPMSOLVER_FILL_MODE_LOWER, n, da.cupmdata(), lda, mcu->d_fact_work, mcu->d_fact_lwork, mcu->d_fact_info));
1689     PetscCall(PetscLogGpuTimeEnd());
1690   }
1691   PetscCall(CheckCUPMSolverInfo_(mcu->d_fact_info, stream));
1692   // TODO (write cuda kernel)
1693   PetscCall(MatSeqDenseSymmetrize_Private(A, PETSC_TRUE));
1694   PetscCall(PetscLogGpuFlops(1.0 * n * n * n / 3.0));
1695 
1696   A->ops->solve          = nullptr;
1697   A->ops->solvetranspose = nullptr;
1698   A->ops->matsolve       = nullptr;
1699   A->factortype          = MAT_FACTOR_NONE;
1700 
1701   PetscCall(PetscFree(A->solvertype));
1702   PetscFunctionReturn(PETSC_SUCCESS);
1703 }
1704 
1705 // ==========================================================================================
1706 
1707 template <device::cupm::DeviceType T>
1708 inline PetscErrorCode MatDense_Seq_CUPM<T>::GetSubMatrix(Mat A, PetscInt rbegin, PetscInt rend, PetscInt cbegin, PetscInt cend, Mat *mat) noexcept
1709 {
1710   const auto         mimpl        = MatIMPLCast(A);
1711   const auto         array_offset = [&](PetscScalar *ptr) { return ptr + rbegin + static_cast<std::size_t>(cbegin) * mimpl->lda; };
1712   const auto         n            = rend - rbegin;
1713   const auto         m            = cend - cbegin;
1714   auto              &cmat         = mimpl->cmat;
1715   PetscDeviceContext dctx;
1716 
1717   PetscFunctionBegin;
1718   PetscCheck(!mimpl->vecinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreColumnVec() first");
1719   PetscCheck(!mimpl->matinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseRestoreSubMatrix() first");
1720   mimpl->matinuse = cbegin + 1;
1721 
1722   PetscCall(GetHandles_(&dctx));
1723   PetscCall(HostToDevice_(A, dctx));
1724 
1725   if (cmat && ((m != cmat->cmap->N) || (n != cmat->rmap->N))) PetscCall(MatDestroy(&cmat));
1726   {
1727     const auto device_array = array_offset(MatCUPMCast(A)->d_v);
1728 
1729     if (cmat) {
1730       PetscCall(PlaceArray(cmat, device_array));
1731     } else {
1732       PetscCall(MatCreateSeqDenseCUPM<T>(PetscObjectComm(PetscObjectCast(A)), n, m, device_array, &cmat, dctx));
1733     }
1734   }
1735   PetscCall(MatDenseSetLDA(cmat, mimpl->lda));
1736   // place CPU array if present but do not copy any data
1737   if (const auto host_array = mimpl->v) {
1738     cmat->offloadmask = PETSC_OFFLOAD_GPU;
1739     PetscCall(MatDensePlaceArray(cmat, array_offset(host_array)));
1740   }
1741 
1742   cmat->offloadmask = A->offloadmask;
1743   *mat              = cmat;
1744   PetscFunctionReturn(PETSC_SUCCESS);
1745 }
1746 
1747 template <device::cupm::DeviceType T>
1748 inline PetscErrorCode MatDense_Seq_CUPM<T>::RestoreSubMatrix(Mat A, Mat *m) noexcept
1749 {
1750   const auto mimpl = MatIMPLCast(A);
1751   const auto cmat  = mimpl->cmat;
1752   const auto reset = static_cast<bool>(mimpl->v);
1753   bool       copy, was_offload_host;
1754 
1755   PetscFunctionBegin;
1756   PetscCheck(mimpl->matinuse, PETSC_COMM_SELF, PETSC_ERR_ORDER, "Need to call MatDenseGetSubMatrix() first");
1757   PetscCheck(cmat, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Missing internal column matrix");
1758   PetscCheck(*m == cmat, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Not the matrix obtained from MatDenseGetSubMatrix()");
1759   mimpl->matinuse = 0;
1760 
1761   // calls to ResetArray may change it, so save it here
1762   was_offload_host = cmat->offloadmask == PETSC_OFFLOAD_CPU;
1763   if (was_offload_host && !reset) {
1764     copy = true;
1765     PetscCall(MatSeqDenseSetPreallocation(A, nullptr));
1766   } else {
1767     copy = false;
1768   }
1769 
1770   PetscCall(ResetArray(cmat));
1771   if (reset) PetscCall(MatDenseResetArray(cmat));
1772   if (copy) {
1773     PetscDeviceContext dctx;
1774 
1775     PetscCall(GetHandles_(&dctx));
1776     PetscCall(DeviceToHost_(A, dctx));
1777   } else {
1778     A->offloadmask = was_offload_host ? PETSC_OFFLOAD_CPU : PETSC_OFFLOAD_GPU;
1779   }
1780 
1781   cmat->offloadmask = PETSC_OFFLOAD_UNALLOCATED;
1782   *m                = nullptr;
1783   PetscFunctionReturn(PETSC_SUCCESS);
1784 }
1785 
1786 // ==========================================================================================
1787 
1788 namespace
1789 {
1790 
1791 template <device::cupm::DeviceType T>
1792 inline PetscErrorCode MatMatMultNumeric_SeqDenseCUPM_SeqDenseCUPM(Mat A, Mat B, Mat C, PetscBool TA, PetscBool TB) noexcept
1793 {
1794   PetscFunctionBegin;
1795   if (TA) {
1796     if (TB) {
1797       PetscCall(MatDense_Seq_CUPM<T>::template MatMatMult_Numeric_Dispatch<true, true>(A, B, C));
1798     } else {
1799       PetscCall(MatDense_Seq_CUPM<T>::template MatMatMult_Numeric_Dispatch<true, false>(A, B, C));
1800     }
1801   } else {
1802     if (TB) {
1803       PetscCall(MatDense_Seq_CUPM<T>::template MatMatMult_Numeric_Dispatch<false, true>(A, B, C));
1804     } else {
1805       PetscCall(MatDense_Seq_CUPM<T>::template MatMatMult_Numeric_Dispatch<false, false>(A, B, C));
1806     }
1807   }
1808   PetscFunctionReturn(PETSC_SUCCESS);
1809 }
1810 
1811 template <device::cupm::DeviceType T>
1812 inline PetscErrorCode MatSolverTypeRegister_DENSECUPM() noexcept
1813 {
1814   PetscFunctionBegin;
1815   for (auto ftype : util::make_array(MAT_FACTOR_LU, MAT_FACTOR_CHOLESKY, MAT_FACTOR_QR)) {
1816     PetscCall(MatSolverTypeRegister(MatDense_Seq_CUPM<T>::MATSOLVERCUPM(), MATSEQDENSE, ftype, MatDense_Seq_CUPM<T>::GetFactor));
1817     PetscCall(MatSolverTypeRegister(MatDense_Seq_CUPM<T>::MATSOLVERCUPM(), MatDense_Seq_CUPM<T>::MATSEQDENSECUPM(), ftype, MatDense_Seq_CUPM<T>::GetFactor));
1818   }
1819   PetscFunctionReturn(PETSC_SUCCESS);
1820 }
1821 
1822 } // anonymous namespace
1823 
1824 } // namespace impl
1825 
1826 } // namespace cupm
1827 
1828 } // namespace mat
1829 
1830 } // namespace Petsc
1831