Actual source code: aijkok.kokkos.cxx
1: #include <petsc_kokkos.hpp>
2: #include <petscvec_kokkos.hpp>
3: #include <petscmat_kokkos.hpp>
4: #include <petscpkg_version.h>
5: #include <petsc/private/petscimpl.h>
6: #include <petsc/private/sfimpl.h>
7: #include <petsc/private/kokkosimpl.hpp>
8: #include <petscsys.h>
10: PETSC_PRAGMA_DIAGNOSTIC_IGNORED_BEGIN("-Wundef")
11: #include <KokkosBlas.hpp>
12: PETSC_PRAGMA_DIAGNOSTIC_IGNORED_END()
13: #include <KokkosSparse_CrsMatrix.hpp>
15: // To suppress compiler warnings:
16: // /path/include/KokkosSparse_spmv_bsrmatrix_tpl_spec_decl.hpp:434:63:
17: // warning: 'cusparseStatus_t cusparseDbsrmm(cusparseHandle_t, cusparseDirection_t, cusparseOperation_t,
18: // cusparseOperation_t, int, int, int, int, const double*, cusparseMatDescr_t, const double*, const int*, const int*,
19: // int, const double*, int, const double*, double*, int)' is deprecated: please use cusparseSpMM instead [-Wdeprecated-declarations]
20: #define DISABLE_CUSPARSE_DEPRECATED
21: #include <KokkosSparse_spmv.hpp>
23: PETSC_PRAGMA_DIAGNOSTIC_IGNORED_BEGIN("-Wundef")
24: #include <KokkosSparse_spiluk.hpp>
25: PETSC_PRAGMA_DIAGNOSTIC_IGNORED_END()
26: #include <KokkosSparse_sptrsv.hpp>
27: #include <KokkosSparse_spgemm.hpp>
28: #include <KokkosSparse_spadd.hpp>
29: #include <KokkosBatched_LU_Decl.hpp>
30: #include <KokkosBatched_InverseLU_Decl.hpp>
32: #include <../src/mat/impls/aij/seq/kokkos/aijkok.hpp>
34: #if PETSC_PKG_KOKKOS_KERNELS_VERSION_GE(3, 7, 0)
35: #include <KokkosSparse_Utils.hpp>
36: using KokkosSparse::sort_crs_matrix;
37: using KokkosSparse::Impl::transpose_matrix;
38: #else
39: #include <KokkosKernels_Sorting.hpp>
40: using KokkosKernels::sort_crs_matrix;
41: using KokkosKernels::Impl::transpose_matrix;
42: #endif
44: #if PETSC_PKG_KOKKOS_KERNELS_VERSION_GE(4, 6, 0)
45: using KokkosSparse::spiluk_symbolic;
46: using KokkosSparse::spiluk_numeric;
47: using KokkosSparse::sptrsv_symbolic;
48: using KokkosSparse::sptrsv_solve;
49: using KokkosSparse::Experimental::SPTRSVAlgorithm;
50: using KokkosSparse::Experimental::SPILUKAlgorithm;
51: #else
52: using KokkosSparse::Experimental::spiluk_symbolic;
53: using KokkosSparse::Experimental::spiluk_numeric;
54: using KokkosSparse::Experimental::sptrsv_symbolic;
55: using KokkosSparse::Experimental::sptrsv_solve;
56: using KokkosSparse::Experimental::SPTRSVAlgorithm;
57: using KokkosSparse::Experimental::SPILUKAlgorithm;
58: #endif
60: static PetscErrorCode MatSetOps_SeqAIJKokkos(Mat); /* Forward declaration */
62: /* MatAssemblyEnd_SeqAIJKokkos() happens when we finalized nonzeros of the matrix, either after
63: we assembled the matrix on host, or after we directly produced the matrix data on device (ex., through MatMatMult).
64: In the latter case, it is important to set a_dual's sync state correctly.
65: */
66: static PetscErrorCode MatAssemblyEnd_SeqAIJKokkos(Mat A, MatAssemblyType mode)
67: {
68: Mat_SeqAIJ *aijseq;
69: Mat_SeqAIJKokkos *aijkok;
71: PetscFunctionBegin;
72: if (mode == MAT_FLUSH_ASSEMBLY) PetscFunctionReturn(PETSC_SUCCESS);
73: PetscCall(MatAssemblyEnd_SeqAIJ(A, mode));
75: aijseq = static_cast<Mat_SeqAIJ *>(A->data);
76: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
78: /* If aijkok does not exist, we just copy i, j to device.
79: If aijkok already exists, but the device's nonzero pattern does not match with the host's, we assume the latest data is on host.
80: In both cases, we build a new aijkok structure.
81: */
82: if (!aijkok || aijkok->nonzerostate != A->nonzerostate) { /* aijkok might not exist yet or nonzero pattern has changed */
83: if (aijkok && aijkok->host_aij_allocated_by_kokkos) { /* Avoid accidentally freeing much needed a,i,j on host when deleting aijkok */
84: PetscCall(PetscShmgetAllocateArray(aijkok->nrows() + 1, sizeof(PetscInt), (void **)&aijseq->i));
85: PetscCall(PetscShmgetAllocateArray(aijkok->nnz(), sizeof(PetscInt), (void **)&aijseq->j));
86: PetscCall(PetscShmgetAllocateArray(aijkok->nnz(), sizeof(PetscInt), (void **)&aijseq->a));
87: PetscCall(PetscArraycpy(aijseq->i, aijkok->i_host_data(), aijkok->nrows() + 1));
88: PetscCall(PetscArraycpy(aijseq->j, aijkok->j_host_data(), aijkok->nnz()));
89: PetscCall(PetscArraycpy(aijseq->a, aijkok->a_host_data(), aijkok->nnz()));
90: aijseq->free_a = PETSC_TRUE;
91: aijseq->free_ij = PETSC_TRUE;
92: /* This arises from MatCreateSeqAIJKokkosWithKokkosCsrMatrix() used in MatMatMult, where
93: we have the CsrMatrix on device first and then copy to host, followed by
94: MatSetMPIAIJWithSplitSeqAIJ() with garray = NULL.
95: One could improve it by not using NULL garray.
96: */
97: }
98: delete aijkok;
99: aijkok = new Mat_SeqAIJKokkos(A, A->rmap->n, A->cmap->n, aijseq, A->nonzerostate, PETSC_FALSE /* don't copy mat values to device */);
100: A->spptr = aijkok;
101: } else if (A->rmap->n && aijkok->diag_dual.extent(0) == 0) { // MatProduct might directly produce AIJ on device, but not the diag.
102: const PetscInt *adiag;
103: /* the a->diag is created at assmebly here because the rest of the Kokkos AIJ code assumes it always exists. This needs to be fixed since it is now only created when needed! */
104: PetscCall(MatGetDiagonalMarkers_SeqAIJ(A, &adiag, NULL));
105: MatRowMapKokkosViewHost diag_h(aijseq->diag, A->rmap->n);
106: auto diag_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), diag_h);
107: aijkok->diag_dual = MatRowMapKokkosDualView(diag_d, diag_h);
108: }
109: PetscFunctionReturn(PETSC_SUCCESS);
110: }
112: /* Sync CSR data to device if not yet */
113: PETSC_INTERN PetscErrorCode MatSeqAIJKokkosSyncDevice(Mat A)
114: {
115: Mat_SeqAIJKokkos *aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
117: PetscFunctionBegin;
118: PetscCheck(A->factortype == MAT_FACTOR_NONE, PetscObjectComm((PetscObject)A), PETSC_ERR_PLIB, "Can't sync factorized matrix from host to device");
119: PetscCheck(aijkok, PETSC_COMM_WORLD, PETSC_ERR_PLIB, "Unexpected NULL (Mat_SeqAIJKokkos*)A->spptr");
120: if (aijkok->a_dual.need_sync_device()) {
121: PetscCall(KokkosDualViewSyncDevice(aijkok->a_dual, PetscGetKokkosExecutionSpace()));
122: aijkok->transpose_updated = PETSC_FALSE; /* values of the transpose is out-of-date */
123: aijkok->hermitian_updated = PETSC_FALSE;
124: }
125: PetscFunctionReturn(PETSC_SUCCESS);
126: }
128: /* Mark the CSR data on device as modified */
129: PETSC_INTERN PetscErrorCode MatSeqAIJKokkosModifyDevice(Mat A)
130: {
131: Mat_SeqAIJKokkos *aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
133: PetscFunctionBegin;
134: PetscCheck(A->factortype == MAT_FACTOR_NONE, PetscObjectComm((PetscObject)A), PETSC_ERR_PLIB, "Not supported for factorized matries");
135: aijkok->a_dual.clear_sync_state();
136: aijkok->a_dual.modify_device();
137: aijkok->transpose_updated = PETSC_FALSE;
138: aijkok->hermitian_updated = PETSC_FALSE;
139: PetscCall(PetscObjectStateIncrease((PetscObject)A));
140: PetscFunctionReturn(PETSC_SUCCESS);
141: }
143: static PetscErrorCode MatSeqAIJKokkosSyncHost(Mat A)
144: {
145: Mat_SeqAIJKokkos *aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
146: auto exec = PetscGetKokkosExecutionSpace();
148: PetscFunctionBegin;
149: PetscCheckTypeName(A, MATSEQAIJKOKKOS);
150: /* We do not expect one needs factors on host */
151: PetscCheck(A->factortype == MAT_FACTOR_NONE, PetscObjectComm((PetscObject)A), PETSC_ERR_PLIB, "Can't sync factorized matrix from device to host");
152: PetscCheck(aijkok, PetscObjectComm((PetscObject)A), PETSC_ERR_PLIB, "Missing AIJKOK");
153: PetscCall(KokkosDualViewSyncHost(aijkok->a_dual, exec));
154: PetscFunctionReturn(PETSC_SUCCESS);
155: }
157: static PetscErrorCode MatSeqAIJGetArray_SeqAIJKokkos(Mat A, PetscScalar *array[])
158: {
159: Mat_SeqAIJKokkos *aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
161: PetscFunctionBegin;
162: /* aijkok contains valid pointers only if the host's nonzerostate matches with the device's.
163: Calling MatSeqAIJSetPreallocation() or MatSetValues() on host, where aijseq->{i,j,a} might be
164: reallocated, will lead to stale {i,j,a}_dual in aijkok. In both operations, the hosts's nonzerostate
165: must have been updated. The stale aijkok will be rebuilt during MatAssemblyEnd.
166: */
167: if (aijkok && A->nonzerostate == aijkok->nonzerostate) {
168: PetscCall(KokkosDualViewSyncHost(aijkok->a_dual, PetscGetKokkosExecutionSpace()));
169: *array = aijkok->a_dual.view_host().data();
170: } else { /* Happens when calling MatSetValues on a newly created matrix */
171: *array = static_cast<Mat_SeqAIJ *>(A->data)->a;
172: }
173: PetscFunctionReturn(PETSC_SUCCESS);
174: }
176: static PetscErrorCode MatSeqAIJRestoreArray_SeqAIJKokkos(Mat A, PetscScalar *array[])
177: {
178: Mat_SeqAIJKokkos *aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
180: PetscFunctionBegin;
181: if (aijkok && A->nonzerostate == aijkok->nonzerostate) aijkok->a_dual.modify_host();
182: PetscFunctionReturn(PETSC_SUCCESS);
183: }
185: static PetscErrorCode MatSeqAIJGetArrayRead_SeqAIJKokkos(Mat A, const PetscScalar *array[])
186: {
187: Mat_SeqAIJKokkos *aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
189: PetscFunctionBegin;
190: if (aijkok && A->nonzerostate == aijkok->nonzerostate) {
191: PetscCall(KokkosDualViewSyncHost(aijkok->a_dual, PetscGetKokkosExecutionSpace()));
192: *array = aijkok->a_dual.view_host().data();
193: } else {
194: *array = static_cast<Mat_SeqAIJ *>(A->data)->a;
195: }
196: PetscFunctionReturn(PETSC_SUCCESS);
197: }
199: static PetscErrorCode MatSeqAIJRestoreArrayRead_SeqAIJKokkos(Mat A, const PetscScalar *array[])
200: {
201: PetscFunctionBegin;
202: *array = NULL;
203: PetscFunctionReturn(PETSC_SUCCESS);
204: }
206: static PetscErrorCode MatSeqAIJGetArrayWrite_SeqAIJKokkos(Mat A, PetscScalar *array[])
207: {
208: Mat_SeqAIJKokkos *aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
210: PetscFunctionBegin;
211: if (aijkok && A->nonzerostate == aijkok->nonzerostate) {
212: *array = aijkok->a_dual.view_host().data();
213: } else { /* Ex. happens with MatZeroEntries on a preallocated but not assembled matrix */
214: *array = static_cast<Mat_SeqAIJ *>(A->data)->a;
215: }
216: PetscFunctionReturn(PETSC_SUCCESS);
217: }
219: static PetscErrorCode MatSeqAIJRestoreArrayWrite_SeqAIJKokkos(Mat A, PetscScalar *array[])
220: {
221: Mat_SeqAIJKokkos *aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
223: PetscFunctionBegin;
224: if (aijkok && A->nonzerostate == aijkok->nonzerostate) {
225: aijkok->a_dual.clear_sync_state();
226: aijkok->a_dual.modify_host();
227: }
228: PetscFunctionReturn(PETSC_SUCCESS);
229: }
231: static PetscErrorCode MatSeqAIJGetCSRAndMemType_SeqAIJKokkos(Mat A, const PetscInt **i, const PetscInt **j, PetscScalar **a, PetscMemType *mtype)
232: {
233: Mat_SeqAIJKokkos *aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
235: PetscFunctionBegin;
236: PetscCheck(aijkok != NULL, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "aijkok is NULL");
238: if (i) *i = aijkok->i_device_data();
239: if (j) *j = aijkok->j_device_data();
240: if (a) {
241: PetscCall(KokkosDualViewSyncDevice(aijkok->a_dual, PetscGetKokkosExecutionSpace()));
242: *a = aijkok->a_device_data();
243: }
244: if (mtype) *mtype = PETSC_MEMTYPE_KOKKOS;
245: PetscFunctionReturn(PETSC_SUCCESS);
246: }
248: static PetscErrorCode MatGetCurrentMemType_SeqAIJKokkos(PETSC_UNUSED Mat A, PetscMemType *mtype)
249: {
250: PetscFunctionBegin;
251: *mtype = PETSC_MEMTYPE_KOKKOS;
252: PetscFunctionReturn(PETSC_SUCCESS);
253: }
255: /*
256: Generate the sparsity pattern of a MatSeqAIJKokkos matrix's transpose on device.
258: Input Parameter:
259: . A - the MATSEQAIJKOKKOS matrix
261: Output Parameters:
262: + perm_d - the permutation array on device, which connects Ta(i) = Aa(perm(i))
263: - T_d - the transpose on device, whose value array is allocated but not initialized
264: */
265: static PetscErrorCode MatSeqAIJKokkosGenerateTransposeStructure(Mat A, MatRowMapKokkosView &perm_d, KokkosCsrMatrix &T_d)
266: {
267: Mat_SeqAIJ *aseq = static_cast<Mat_SeqAIJ *>(A->data);
268: PetscInt nz = aseq->nz, m = A->rmap->N, n = A->cmap->n;
269: const PetscInt *Ai = aseq->i, *Aj = aseq->j;
270: MatRowMapKokkosViewHost Ti_h(NoInit("Ti"), n + 1);
271: MatRowMapType *Ti = Ti_h.data();
272: MatColIdxKokkosViewHost Tj_h(NoInit("Tj"), nz);
273: MatRowMapKokkosViewHost perm_h(NoInit("permutation"), nz);
274: PetscInt *Tj = Tj_h.data();
275: PetscInt *perm = perm_h.data();
276: PetscInt *offset;
278: PetscFunctionBegin;
279: // Populate Ti
280: PetscCallCXX(Kokkos::deep_copy(Ti_h, 0));
281: Ti++;
282: for (PetscInt i = 0; i < nz; i++) Ti[Aj[i]]++;
283: Ti--;
284: for (PetscInt i = 0; i < n; i++) Ti[i + 1] += Ti[i];
286: // Populate Tj and the permutation array
287: PetscCall(PetscCalloc1(n, &offset)); // offset in each T row to fill in its column indices
288: for (PetscInt i = 0; i < m; i++) {
289: for (PetscInt j = Ai[i]; j < Ai[i + 1]; j++) { // A's (i,j) is T's (j,i)
290: PetscInt r = Aj[j]; // row r of T
291: PetscInt disp = Ti[r] + offset[r];
293: Tj[disp] = i; // col i of T
294: perm[disp] = j;
295: offset[r]++;
296: }
297: }
298: PetscCall(PetscFree(offset));
300: // Sort each row of T, along with the permutation array
301: for (PetscInt i = 0; i < n; i++) PetscCall(PetscSortIntWithArray(Ti[i + 1] - Ti[i], Tj + Ti[i], perm + Ti[i]));
303: // Output perm and T on device
304: auto Ti_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), Ti_h);
305: auto Tj_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), Tj_h);
306: PetscCallCXX(T_d = KokkosCsrMatrix("csrmatT", n, m, nz, MatScalarKokkosView("Ta", nz), Ti_d, Tj_d));
307: PetscCallCXX(perm_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), perm_h));
308: PetscFunctionReturn(PETSC_SUCCESS);
309: }
311: // Generate the transpose on device and cache it internally
312: // Note: KK transpose_matrix() does not have support symbolic/numeric transpose, so we do it on our own
313: PETSC_INTERN PetscErrorCode MatSeqAIJKokkosGenerateTranspose_Private(Mat A, KokkosCsrMatrix *csrmatT)
314: {
315: Mat_SeqAIJ *aseq = static_cast<Mat_SeqAIJ *>(A->data);
316: Mat_SeqAIJKokkos *akok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
317: PetscInt nz = aseq->nz, m = A->rmap->N, n = A->cmap->n;
318: KokkosCsrMatrix &T = akok->csrmatT;
320: PetscFunctionBegin;
321: PetscCheck(akok, PETSC_COMM_WORLD, PETSC_ERR_PLIB, "Unexpected NULL (Mat_SeqAIJKokkos*)A->spptr");
322: PetscCall(KokkosDualViewSyncDevice(akok->a_dual, PetscGetKokkosExecutionSpace())); // Sync A's values since we are going to access them on device
324: const auto &Aa = akok->a_dual.view_device();
326: if (A->symmetric == PETSC_BOOL3_TRUE) {
327: *csrmatT = akok->csrmat;
328: } else {
329: // See if we already have a cached transpose and its value is up to date
330: if (T.numRows() == n && T.numCols() == m) { // this indicates csrmatT had been generated before, otherwise T has 0 rows/cols after construction
331: if (!akok->transpose_updated) { // if the value is out of date, update the cached version
332: const auto &perm = akok->transpose_perm; // get the permutation array
333: auto &Ta = T.values;
335: PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, nz), KOKKOS_LAMBDA(const PetscInt i) { Ta(i) = Aa(perm(i)); }));
336: }
337: } else { // Generate T of size n x m for the first time
338: MatRowMapKokkosView perm;
340: PetscCall(MatSeqAIJKokkosGenerateTransposeStructure(A, perm, T));
341: akok->transpose_perm = perm; // cache the perm in this matrix for reuse
342: PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, nz), KOKKOS_LAMBDA(const PetscInt i) { T.values(i) = Aa(perm(i)); }));
343: }
344: akok->transpose_updated = PETSC_TRUE;
345: *csrmatT = akok->csrmatT;
346: }
347: PetscFunctionReturn(PETSC_SUCCESS);
348: }
350: // Generate the Hermitian on device and cache it internally
351: static PetscErrorCode MatSeqAIJKokkosGenerateHermitian_Private(Mat A, KokkosCsrMatrix *csrmatH)
352: {
353: Mat_SeqAIJ *aseq = static_cast<Mat_SeqAIJ *>(A->data);
354: Mat_SeqAIJKokkos *akok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
355: PetscInt nz = aseq->nz, m = A->rmap->N, n = A->cmap->n;
356: KokkosCsrMatrix &T = akok->csrmatH;
358: PetscFunctionBegin;
359: PetscCheck(akok, PETSC_COMM_WORLD, PETSC_ERR_PLIB, "Unexpected NULL (Mat_SeqAIJKokkos*)A->spptr");
360: PetscCall(KokkosDualViewSyncDevice(akok->a_dual, PetscGetKokkosExecutionSpace())); // Sync A's values since we are going to access them on device
362: const auto &Aa = akok->a_dual.view_device();
364: if (A->hermitian == PETSC_BOOL3_TRUE) {
365: *csrmatH = akok->csrmat;
366: } else {
367: // See if we already have a cached Hermitian and its value is up to date
368: if (T.numRows() == n && T.numCols() == m) { // this indicates csrmatT had been generated before, otherwise T has 0 rows/cols after construction
369: if (!akok->hermitian_updated) { // if the value is out of date, update the cached version
370: const auto &perm = akok->transpose_perm; // get the permutation array
371: auto &Ta = T.values;
373: PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, nz), KOKKOS_LAMBDA(const PetscInt i) { Ta(i) = PetscConj(Aa(perm(i))); }));
374: }
375: } else { // Generate T of size n x m for the first time
376: MatRowMapKokkosView perm;
378: PetscCall(MatSeqAIJKokkosGenerateTransposeStructure(A, perm, T));
379: akok->transpose_perm = perm; // cache the perm in this matrix for reuse
380: PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, nz), KOKKOS_LAMBDA(const PetscInt i) { T.values(i) = PetscConj(Aa(perm(i))); }));
381: }
382: akok->hermitian_updated = PETSC_TRUE;
383: *csrmatH = akok->csrmatH;
384: }
385: PetscFunctionReturn(PETSC_SUCCESS);
386: }
388: /* y = A x */
389: static PetscErrorCode MatMult_SeqAIJKokkos(Mat A, Vec xx, Vec yy)
390: {
391: Mat_SeqAIJKokkos *aijkok;
392: ConstPetscScalarKokkosView xv;
393: PetscScalarKokkosView yv;
395: PetscFunctionBegin;
396: PetscCall(PetscLogGpuTimeBegin());
397: PetscCall(MatSeqAIJKokkosSyncDevice(A));
398: PetscCall(VecGetKokkosView(xx, &xv));
399: PetscCall(VecGetKokkosViewWrite(yy, &yv));
400: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
401: PetscCallCXX(KokkosSparse::spmv(PetscGetKokkosExecutionSpace(), "N", 1.0 /*alpha*/, aijkok->csrmat, xv, 0.0 /*beta*/, yv)); /* y = alpha A x + beta y */
402: PetscCall(VecRestoreKokkosView(xx, &xv));
403: PetscCall(VecRestoreKokkosViewWrite(yy, &yv));
404: /* 2.0*nnz - numRows seems more accurate here but assumes there are no zero-rows. So a little sloppy here. */
405: PetscCall(PetscLogGpuFlops(2.0 * aijkok->csrmat.nnz()));
406: PetscCall(PetscLogGpuTimeEnd());
407: PetscFunctionReturn(PETSC_SUCCESS);
408: }
410: /* y = A^T x */
411: static PetscErrorCode MatMultTranspose_SeqAIJKokkos(Mat A, Vec xx, Vec yy)
412: {
413: Mat_SeqAIJKokkos *aijkok;
414: const char *mode;
415: ConstPetscScalarKokkosView xv;
416: PetscScalarKokkosView yv;
417: KokkosCsrMatrix csrmat;
419: PetscFunctionBegin;
420: PetscCall(PetscLogGpuTimeBegin());
421: PetscCall(MatSeqAIJKokkosSyncDevice(A));
422: PetscCall(VecGetKokkosView(xx, &xv));
423: PetscCall(VecGetKokkosViewWrite(yy, &yv));
424: if (A->form_explicit_transpose) {
425: PetscCall(MatSeqAIJKokkosGenerateTranspose_Private(A, &csrmat));
426: mode = "N";
427: } else {
428: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
429: csrmat = aijkok->csrmat;
430: mode = "T";
431: }
432: PetscCallCXX(KokkosSparse::spmv(PetscGetKokkosExecutionSpace(), mode, 1.0 /*alpha*/, csrmat, xv, 0.0 /*beta*/, yv)); /* y = alpha A^T x + beta y */
433: PetscCall(VecRestoreKokkosView(xx, &xv));
434: PetscCall(VecRestoreKokkosViewWrite(yy, &yv));
435: PetscCall(PetscLogGpuFlops(2.0 * csrmat.nnz()));
436: PetscCall(PetscLogGpuTimeEnd());
437: PetscFunctionReturn(PETSC_SUCCESS);
438: }
440: /* y = A^H x */
441: static PetscErrorCode MatMultHermitianTranspose_SeqAIJKokkos(Mat A, Vec xx, Vec yy)
442: {
443: Mat_SeqAIJKokkos *aijkok;
444: const char *mode;
445: ConstPetscScalarKokkosView xv;
446: PetscScalarKokkosView yv;
447: KokkosCsrMatrix csrmat;
449: PetscFunctionBegin;
450: PetscCall(PetscLogGpuTimeBegin());
451: PetscCall(MatSeqAIJKokkosSyncDevice(A));
452: PetscCall(VecGetKokkosView(xx, &xv));
453: PetscCall(VecGetKokkosViewWrite(yy, &yv));
454: if (A->form_explicit_transpose) {
455: PetscCall(MatSeqAIJKokkosGenerateHermitian_Private(A, &csrmat));
456: mode = "N";
457: } else {
458: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
459: csrmat = aijkok->csrmat;
460: mode = "C";
461: }
462: PetscCallCXX(KokkosSparse::spmv(PetscGetKokkosExecutionSpace(), mode, 1.0 /*alpha*/, csrmat, xv, 0.0 /*beta*/, yv)); /* y = alpha A^H x + beta y */
463: PetscCall(VecRestoreKokkosView(xx, &xv));
464: PetscCall(VecRestoreKokkosViewWrite(yy, &yv));
465: PetscCall(PetscLogGpuFlops(2.0 * csrmat.nnz()));
466: PetscCall(PetscLogGpuTimeEnd());
467: PetscFunctionReturn(PETSC_SUCCESS);
468: }
470: /* z = A x + y */
471: static PetscErrorCode MatMultAdd_SeqAIJKokkos(Mat A, Vec xx, Vec yy, Vec zz)
472: {
473: Mat_SeqAIJKokkos *aijkok;
474: ConstPetscScalarKokkosView xv;
475: PetscScalarKokkosView zv;
477: PetscFunctionBegin;
478: PetscCall(PetscLogGpuTimeBegin());
479: PetscCall(MatSeqAIJKokkosSyncDevice(A));
480: if (zz != yy) PetscCall(VecCopy(yy, zz)); // depending on yy's sync flags, zz might get its latest data on host
481: PetscCall(VecGetKokkosView(xx, &xv));
482: PetscCall(VecGetKokkosView(zz, &zv)); // do after VecCopy(yy, zz) to get the latest data on device
483: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
484: PetscCallCXX(KokkosSparse::spmv(PetscGetKokkosExecutionSpace(), "N", 1.0 /*alpha*/, aijkok->csrmat, xv, 1.0 /*beta*/, zv)); /* z = alpha A x + beta z */
485: PetscCall(VecRestoreKokkosView(xx, &xv));
486: PetscCall(VecRestoreKokkosView(zz, &zv));
487: PetscCall(PetscLogGpuFlops(2.0 * aijkok->csrmat.nnz()));
488: PetscCall(PetscLogGpuTimeEnd());
489: PetscFunctionReturn(PETSC_SUCCESS);
490: }
492: /* z = A^T x + y */
493: static PetscErrorCode MatMultTransposeAdd_SeqAIJKokkos(Mat A, Vec xx, Vec yy, Vec zz)
494: {
495: Mat_SeqAIJKokkos *aijkok;
496: const char *mode;
497: ConstPetscScalarKokkosView xv;
498: PetscScalarKokkosView zv;
499: KokkosCsrMatrix csrmat;
501: PetscFunctionBegin;
502: PetscCall(PetscLogGpuTimeBegin());
503: PetscCall(MatSeqAIJKokkosSyncDevice(A));
504: if (zz != yy) PetscCall(VecCopy(yy, zz));
505: PetscCall(VecGetKokkosView(xx, &xv));
506: PetscCall(VecGetKokkosView(zz, &zv));
507: if (A->form_explicit_transpose) {
508: PetscCall(MatSeqAIJKokkosGenerateTranspose_Private(A, &csrmat));
509: mode = "N";
510: } else {
511: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
512: csrmat = aijkok->csrmat;
513: mode = "T";
514: }
515: PetscCallCXX(KokkosSparse::spmv(PetscGetKokkosExecutionSpace(), mode, 1.0 /*alpha*/, csrmat, xv, 1.0 /*beta*/, zv)); /* z = alpha A^T x + beta z */
516: PetscCall(VecRestoreKokkosView(xx, &xv));
517: PetscCall(VecRestoreKokkosView(zz, &zv));
518: PetscCall(PetscLogGpuFlops(2.0 * csrmat.nnz()));
519: PetscCall(PetscLogGpuTimeEnd());
520: PetscFunctionReturn(PETSC_SUCCESS);
521: }
523: /* z = A^H x + y */
524: static PetscErrorCode MatMultHermitianTransposeAdd_SeqAIJKokkos(Mat A, Vec xx, Vec yy, Vec zz)
525: {
526: Mat_SeqAIJKokkos *aijkok;
527: const char *mode;
528: ConstPetscScalarKokkosView xv;
529: PetscScalarKokkosView zv;
530: KokkosCsrMatrix csrmat;
532: PetscFunctionBegin;
533: PetscCall(PetscLogGpuTimeBegin());
534: PetscCall(MatSeqAIJKokkosSyncDevice(A));
535: if (zz != yy) PetscCall(VecCopy(yy, zz));
536: PetscCall(VecGetKokkosView(xx, &xv));
537: PetscCall(VecGetKokkosView(zz, &zv));
538: if (A->form_explicit_transpose) {
539: PetscCall(MatSeqAIJKokkosGenerateHermitian_Private(A, &csrmat));
540: mode = "N";
541: } else {
542: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
543: csrmat = aijkok->csrmat;
544: mode = "C";
545: }
546: PetscCallCXX(KokkosSparse::spmv(PetscGetKokkosExecutionSpace(), mode, 1.0 /*alpha*/, csrmat, xv, 1.0 /*beta*/, zv)); /* z = alpha A^H x + beta z */
547: PetscCall(VecRestoreKokkosView(xx, &xv));
548: PetscCall(VecRestoreKokkosView(zz, &zv));
549: PetscCall(PetscLogGpuFlops(2.0 * csrmat.nnz()));
550: PetscCall(PetscLogGpuTimeEnd());
551: PetscFunctionReturn(PETSC_SUCCESS);
552: }
554: static PetscErrorCode MatSetOption_SeqAIJKokkos(Mat A, MatOption op, PetscBool flg)
555: {
556: Mat_SeqAIJKokkos *aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
558: PetscFunctionBegin;
559: switch (op) {
560: case MAT_FORM_EXPLICIT_TRANSPOSE:
561: /* need to destroy the transpose matrix if present to prevent from logic errors if flg is set to true later */
562: if (A->form_explicit_transpose && !flg && aijkok) PetscCall(aijkok->DestroyMatTranspose());
563: A->form_explicit_transpose = flg;
564: break;
565: default:
566: PetscCall(MatSetOption_SeqAIJ(A, op, flg));
567: break;
568: }
569: PetscFunctionReturn(PETSC_SUCCESS);
570: }
572: /* Depending on reuse, either build a new mat, or use the existing mat */
573: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJKokkos(Mat A, MatType mtype, MatReuse reuse, Mat *newmat)
574: {
575: Mat_SeqAIJ *aseq;
577: PetscFunctionBegin;
578: PetscCall(PetscKokkosInitializeCheck());
579: if (reuse == MAT_INITIAL_MATRIX) { /* Build a brand new mat */
580: PetscCall(MatDuplicate(A, MAT_COPY_VALUES, newmat));
581: PetscCall(MatSetType(*newmat, mtype));
582: } else if (reuse == MAT_REUSE_MATRIX) { /* Reuse the mat created before */
583: PetscCall(MatCopy(A, *newmat, SAME_NONZERO_PATTERN)); /* newmat is already a SeqAIJKokkos */
584: } else if (reuse == MAT_INPLACE_MATRIX) { /* newmat is A */
585: PetscCheck(A == *newmat, PetscObjectComm((PetscObject)A), PETSC_ERR_PLIB, "A != *newmat with MAT_INPLACE_MATRIX");
586: PetscCall(PetscFree(A->defaultvectype));
587: PetscCall(PetscStrallocpy(VECKOKKOS, &A->defaultvectype)); /* Allocate and copy the string */
588: PetscCall(PetscObjectChangeTypeName((PetscObject)A, MATSEQAIJKOKKOS));
589: PetscCall(MatSetOps_SeqAIJKokkos(A));
590: aseq = static_cast<Mat_SeqAIJ *>(A->data);
591: if (A->assembled) { /* Copy i, j (but not values) to device for an assembled matrix if not yet */
592: PetscCheck(!A->spptr, PETSC_COMM_WORLD, PETSC_ERR_PLIB, "Expect NULL (Mat_SeqAIJKokkos*)A->spptr");
593: A->spptr = new Mat_SeqAIJKokkos(A, A->rmap->n, A->cmap->n, aseq, A->nonzerostate, PETSC_FALSE);
594: }
595: }
596: PetscFunctionReturn(PETSC_SUCCESS);
597: }
599: /* MatDuplicate always creates a new matrix. MatDuplicate can be called either on an assembled matrix or
600: an unassembled matrix, even though MAT_COPY_VALUES is not allowed for unassembled matrix.
601: */
602: static PetscErrorCode MatDuplicate_SeqAIJKokkos(Mat A, MatDuplicateOption dupOption, Mat *B)
603: {
604: Mat_SeqAIJ *bseq;
605: Mat_SeqAIJKokkos *akok = static_cast<Mat_SeqAIJKokkos *>(A->spptr), *bkok;
606: Mat mat;
608: PetscFunctionBegin;
609: /* Do not copy values on host as A's latest values might be on device. We don't want to do sync blindly */
610: PetscCall(MatDuplicate_SeqAIJ(A, MAT_DO_NOT_COPY_VALUES, B));
611: mat = *B;
612: if (A->assembled) {
613: bseq = static_cast<Mat_SeqAIJ *>(mat->data);
614: bkok = new Mat_SeqAIJKokkos(mat, mat->rmap->n, mat->cmap->n, bseq, mat->nonzerostate, PETSC_FALSE);
615: bkok->a_dual.clear_sync_state(); /* Clear B's sync state as it will be decided below */
616: /* Now copy values to B if needed */
617: if (dupOption == MAT_COPY_VALUES) {
618: if (akok->a_dual.need_sync_device()) {
619: Kokkos::deep_copy(bkok->a_dual.view_host(), akok->a_dual.view_host());
620: bkok->a_dual.modify_host();
621: } else { /* If device has the latest data, we only copy data on device */
622: Kokkos::deep_copy(bkok->a_dual.view_device(), akok->a_dual.view_device());
623: bkok->a_dual.modify_device();
624: }
625: } else { /* MAT_DO_NOT_COPY_VALUES or MAT_SHARE_NONZERO_PATTERN. B's values should be zeroed */
626: /* B's values on host should be already zeroed by MatDuplicate_SeqAIJ() */
627: bkok->a_dual.modify_host();
628: }
629: mat->spptr = bkok;
630: }
632: PetscCall(PetscFree(mat->defaultvectype));
633: PetscCall(PetscStrallocpy(VECKOKKOS, &mat->defaultvectype)); /* Allocate and copy the string */
634: PetscCall(PetscObjectChangeTypeName((PetscObject)mat, MATSEQAIJKOKKOS));
635: PetscCall(MatSetOps_SeqAIJKokkos(mat));
636: PetscFunctionReturn(PETSC_SUCCESS);
637: }
639: static PetscErrorCode MatTranspose_SeqAIJKokkos(Mat A, MatReuse reuse, Mat *B)
640: {
641: Mat At;
642: KokkosCsrMatrix internT;
643: Mat_SeqAIJKokkos *atkok, *bkok;
645: PetscFunctionBegin;
646: if (reuse == MAT_REUSE_MATRIX) PetscCall(MatTransposeCheckNonzeroState_Private(A, *B));
647: PetscCall(MatSeqAIJKokkosGenerateTranspose_Private(A, &internT)); /* Generate a transpose internally */
648: if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_INPLACE_MATRIX) {
649: /* Deep copy internT, as we want to isolate the internal transpose */
650: PetscCallCXX(atkok = new Mat_SeqAIJKokkos(KokkosCsrMatrix("csrmat", internT)));
651: PetscCall(MatCreateSeqAIJKokkosWithCSRMatrix(PetscObjectComm((PetscObject)A), atkok, &At));
652: if (reuse == MAT_INITIAL_MATRIX) *B = At;
653: else PetscCall(MatHeaderReplace(A, &At)); /* Replace A with At inplace */
654: } else { /* MAT_REUSE_MATRIX, just need to copy values to B on device */
655: if ((*B)->assembled) {
656: bkok = static_cast<Mat_SeqAIJKokkos *>((*B)->spptr);
657: PetscCallCXX(Kokkos::deep_copy(bkok->a_dual.view_device(), internT.values));
658: PetscCall(MatSeqAIJKokkosModifyDevice(*B));
659: } else if ((*B)->preallocated) { /* It is ok for B to be only preallocated, as needed in MatTranspose_MPIAIJ */
660: Mat_SeqAIJ *bseq = static_cast<Mat_SeqAIJ *>((*B)->data);
661: MatScalarKokkosViewHost a_h(bseq->a, internT.nnz()); /* bseq->nz = 0 if unassembled */
662: MatColIdxKokkosViewHost j_h(bseq->j, internT.nnz());
663: PetscCallCXX(Kokkos::deep_copy(a_h, internT.values));
664: PetscCallCXX(Kokkos::deep_copy(j_h, internT.graph.entries));
665: } else SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "B must be assembled or preallocated");
666: }
667: PetscFunctionReturn(PETSC_SUCCESS);
668: }
670: static PetscErrorCode MatDestroy_SeqAIJKokkos(Mat A)
671: {
672: Mat_SeqAIJKokkos *aijkok;
674: PetscFunctionBegin;
675: if (A->factortype == MAT_FACTOR_NONE) {
676: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
677: delete aijkok;
678: } else {
679: delete static_cast<Mat_SeqAIJKokkosTriFactors *>(A->spptr);
680: }
681: A->spptr = NULL;
682: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatFactorGetSolverType_C", NULL));
683: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSetPreallocationCOO_C", NULL));
684: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSetValuesCOO_C", NULL));
685: #if defined(PETSC_HAVE_HYPRE)
686: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaijkokkos_hypre_C", NULL));
687: #endif
688: PetscCall(MatDestroy_SeqAIJ(A));
689: PetscFunctionReturn(PETSC_SUCCESS);
690: }
692: /*MC
693: MATSEQAIJKOKKOS - MATAIJKOKKOS = "(seq)aijkokkos" - A matrix type to be used for sparse matrices with Kokkos
695: A matrix type using Kokkos-Kernels CrsMatrix type for portability across different device types
697: Options Database Key:
698: . -mat_type aijkokkos - sets the matrix type to `MATSEQAIJKOKKOS` during a call to `MatSetFromOptions()`
700: Level: beginner
702: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqAIJKokkos()`, `MATMPIAIJKOKKOS`
703: M*/
704: PETSC_EXTERN PetscErrorCode MatCreate_SeqAIJKokkos(Mat A)
705: {
706: PetscFunctionBegin;
707: PetscCall(PetscKokkosInitializeCheck());
708: PetscCall(MatCreate_SeqAIJ(A));
709: PetscCall(MatConvert_SeqAIJ_SeqAIJKokkos(A, MATSEQAIJKOKKOS, MAT_INPLACE_MATRIX, &A));
710: PetscFunctionReturn(PETSC_SUCCESS);
711: }
713: /* Merge A, B into a matrix C. A is put before B. C's size would be A->rmap->n by (A->cmap->n + B->cmap->n) */
714: PetscErrorCode MatSeqAIJKokkosMergeMats(Mat A, Mat B, MatReuse reuse, Mat *C)
715: {
716: Mat_SeqAIJ *a, *b;
717: Mat_SeqAIJKokkos *akok, *bkok, *ckok;
718: MatScalarKokkosView aa, ba, ca;
719: MatRowMapKokkosView ai, bi, ci;
720: MatColIdxKokkosView aj, bj, cj;
721: PetscInt m, n, nnz, aN;
723: PetscFunctionBegin;
726: PetscAssertPointer(C, 4);
727: PetscCheckTypeName(A, MATSEQAIJKOKKOS);
728: PetscCheckTypeName(B, MATSEQAIJKOKKOS);
729: PetscCheck(A->rmap->n == B->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Invalid number or rows %" PetscInt_FMT " != %" PetscInt_FMT, A->rmap->n, B->rmap->n);
730: PetscCheck(reuse != MAT_INPLACE_MATRIX, PETSC_COMM_SELF, PETSC_ERR_SUP, "MAT_INPLACE_MATRIX not supported");
732: PetscCall(MatSeqAIJKokkosSyncDevice(A));
733: PetscCall(MatSeqAIJKokkosSyncDevice(B));
734: a = static_cast<Mat_SeqAIJ *>(A->data);
735: b = static_cast<Mat_SeqAIJ *>(B->data);
736: akok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
737: bkok = static_cast<Mat_SeqAIJKokkos *>(B->spptr);
738: aa = akok->a_dual.view_device();
739: ai = akok->i_dual.view_device();
740: ba = bkok->a_dual.view_device();
741: bi = bkok->i_dual.view_device();
742: m = A->rmap->n; /* M, N and nnz of C */
743: n = A->cmap->n + B->cmap->n;
744: nnz = a->nz + b->nz;
745: aN = A->cmap->n; /* N of A */
746: if (reuse == MAT_INITIAL_MATRIX) {
747: aj = akok->j_dual.view_device();
748: bj = bkok->j_dual.view_device();
749: auto ca = MatScalarKokkosView("a", aa.extent(0) + ba.extent(0));
750: auto ci = MatRowMapKokkosView("i", ai.extent(0));
751: auto cj = MatColIdxKokkosView("j", aj.extent(0) + bj.extent(0));
753: /* Concatenate A and B in parallel using Kokkos hierarchical parallelism */
754: Kokkos::parallel_for(
755: Kokkos::TeamPolicy<>(PetscGetKokkosExecutionSpace(), m, Kokkos::AUTO()), KOKKOS_LAMBDA(const KokkosTeamMemberType &t) {
756: PetscInt i = t.league_rank(); /* row i */
757: PetscInt coffset = ai(i) + bi(i), alen = ai(i + 1) - ai(i), blen = bi(i + 1) - bi(i);
759: Kokkos::single(Kokkos::PerTeam(t), [=]() { /* this side effect only happens once per whole team */
760: ci(i) = coffset;
761: if (i == m - 1) ci(m) = ai(m) + bi(m);
762: });
764: Kokkos::parallel_for(Kokkos::TeamThreadRange(t, alen + blen), [&](PetscInt k) {
765: if (k < alen) {
766: ca(coffset + k) = aa(ai(i) + k);
767: cj(coffset + k) = aj(ai(i) + k);
768: } else {
769: ca(coffset + k) = ba(bi(i) + k - alen);
770: cj(coffset + k) = bj(bi(i) + k - alen) + aN; /* Entries in B get new column indices in C */
771: }
772: });
773: });
774: PetscCallCXX(ckok = new Mat_SeqAIJKokkos(m, n, nnz, ci, cj, ca));
775: PetscCall(MatCreateSeqAIJKokkosWithCSRMatrix(PETSC_COMM_SELF, ckok, C));
776: } else if (reuse == MAT_REUSE_MATRIX) {
778: PetscCheckTypeName(*C, MATSEQAIJKOKKOS);
779: ckok = static_cast<Mat_SeqAIJKokkos *>((*C)->spptr);
780: ca = ckok->a_dual.view_device();
781: ci = ckok->i_dual.view_device();
783: Kokkos::parallel_for(
784: Kokkos::TeamPolicy<>(PetscGetKokkosExecutionSpace(), m, Kokkos::AUTO()), KOKKOS_LAMBDA(const KokkosTeamMemberType &t) {
785: PetscInt i = t.league_rank(); /* row i */
786: PetscInt alen = ai(i + 1) - ai(i), blen = bi(i + 1) - bi(i);
787: Kokkos::parallel_for(Kokkos::TeamThreadRange(t, alen + blen), [&](PetscInt k) {
788: if (k < alen) ca(ci(i) + k) = aa(ai(i) + k);
789: else ca(ci(i) + k) = ba(bi(i) + k - alen);
790: });
791: });
792: PetscCall(MatSeqAIJKokkosModifyDevice(*C));
793: }
794: PetscFunctionReturn(PETSC_SUCCESS);
795: }
797: static PetscErrorCode MatProductCtxDestroy_SeqAIJKokkos(PetscCtxRt pdata)
798: {
799: PetscFunctionBegin;
800: delete *reinterpret_cast<MatProductCtx_SeqAIJKokkos **>(pdata);
801: PetscFunctionReturn(PETSC_SUCCESS);
802: }
804: static PetscErrorCode MatProductNumeric_SeqAIJKokkos_SeqAIJKokkos(Mat C)
805: {
806: Mat_Product *product = C->product;
807: Mat A, B;
808: bool transA, transB; /* use bool, since KK needs this type */
809: Mat_SeqAIJKokkos *akok, *bkok, *ckok;
810: Mat_SeqAIJ *c;
811: MatProductCtx_SeqAIJKokkos *pdata;
812: KokkosCsrMatrix csrmatA, csrmatB;
814: PetscFunctionBegin;
815: MatCheckProduct(C, 1);
816: PetscCheck(C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data empty");
817: pdata = static_cast<MatProductCtx_SeqAIJKokkos *>(C->product->data);
819: // See if numeric has already been done in symbolic (e.g., user calls MatMatMult(A,B,MAT_INITIAL_MATRIX,..,C)).
820: // If yes, skip the numeric, but reset the flag so that next time when user calls MatMatMult(E,F,MAT_REUSE_MATRIX,..,C),
821: // we still do numeric.
822: if (pdata->reusesym) { // numeric reuses results from symbolic
823: pdata->reusesym = PETSC_FALSE;
824: PetscFunctionReturn(PETSC_SUCCESS);
825: }
827: switch (product->type) {
828: case MATPRODUCT_AB:
829: transA = false;
830: transB = false;
831: break;
832: case MATPRODUCT_AtB:
833: transA = true;
834: transB = false;
835: break;
836: case MATPRODUCT_ABt:
837: transA = false;
838: transB = true;
839: break;
840: default:
841: SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Unsupported product type %s", MatProductTypes[product->type]);
842: }
844: A = product->A;
845: B = product->B;
846: PetscCall(MatSeqAIJKokkosSyncDevice(A));
847: PetscCall(MatSeqAIJKokkosSyncDevice(B));
848: akok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
849: bkok = static_cast<Mat_SeqAIJKokkos *>(B->spptr);
850: ckok = static_cast<Mat_SeqAIJKokkos *>(C->spptr);
852: PetscCheck(ckok, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Device data structure spptr is empty");
854: csrmatA = akok->csrmat;
855: csrmatB = bkok->csrmat;
857: /* TODO: Once KK spgemm implements transpose, we can get rid of the explicit transpose here */
858: if (transA) {
859: PetscCall(MatSeqAIJKokkosGenerateTranspose_Private(A, &csrmatA));
860: transA = false;
861: }
863: if (transB) {
864: PetscCall(MatSeqAIJKokkosGenerateTranspose_Private(B, &csrmatB));
865: transB = false;
866: }
867: PetscCall(PetscLogGpuTimeBegin());
868: PetscCallCXX(KokkosSparse::spgemm_numeric(pdata->kh, csrmatA, transA, csrmatB, transB, ckok->csrmat));
869: #if PETSC_PKG_KOKKOS_KERNELS_VERSION_LT(4, 0, 0)
870: auto spgemmHandle = pdata->kh.get_spgemm_handle();
871: if (spgemmHandle->get_sort_option() != 1) PetscCallCXX(sort_crs_matrix(ckok->csrmat)); /* without sort, mat_tests-ex62_14_seqaijkokkos fails */
872: #endif
874: PetscCall(PetscLogGpuTimeEnd());
875: PetscCall(MatSeqAIJKokkosModifyDevice(C));
876: /* shorter version of MatAssemblyEnd_SeqAIJ */
877: c = (Mat_SeqAIJ *)C->data;
878: PetscCall(PetscInfo(C, "Matrix size: %" PetscInt_FMT " X %" PetscInt_FMT "; storage space: 0 unneeded, %" PetscInt_FMT " used\n", C->rmap->n, C->cmap->n, c->nz));
879: PetscCall(PetscInfo(C, "Number of mallocs during MatSetValues() is 0\n"));
880: PetscCall(PetscInfo(C, "Maximum nonzeros in any row is %" PetscInt_FMT "\n", c->rmax));
881: c->reallocs = 0;
882: C->info.mallocs = 0;
883: C->info.nz_unneeded = 0;
884: C->assembled = C->was_assembled = PETSC_TRUE;
885: C->num_ass++;
886: PetscFunctionReturn(PETSC_SUCCESS);
887: }
889: static PetscErrorCode MatProductSymbolic_SeqAIJKokkos_SeqAIJKokkos(Mat C)
890: {
891: Mat_Product *product = C->product;
892: MatProductType ptype;
893: Mat A, B;
894: bool transA, transB;
895: Mat_SeqAIJKokkos *akok, *bkok, *ckok;
896: MatProductCtx_SeqAIJKokkos *pdata;
897: MPI_Comm comm;
898: KokkosCsrMatrix csrmatA, csrmatB, csrmatC;
900: PetscFunctionBegin;
901: MatCheckProduct(C, 1);
902: PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
903: PetscCheck(!product->data, comm, PETSC_ERR_PLIB, "Product data not empty");
904: A = product->A;
905: B = product->B;
906: PetscCall(MatSeqAIJKokkosSyncDevice(A));
907: PetscCall(MatSeqAIJKokkosSyncDevice(B));
908: akok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
909: bkok = static_cast<Mat_SeqAIJKokkos *>(B->spptr);
910: csrmatA = akok->csrmat;
911: csrmatB = bkok->csrmat;
913: ptype = product->type;
914: // Take advantage of the symmetry if true
915: if (A->symmetric == PETSC_BOOL3_TRUE && ptype == MATPRODUCT_AtB) {
916: ptype = MATPRODUCT_AB;
917: product->symbolic_used_the_fact_A_is_symmetric = PETSC_TRUE;
918: }
919: if (B->symmetric == PETSC_BOOL3_TRUE && ptype == MATPRODUCT_ABt) {
920: ptype = MATPRODUCT_AB;
921: product->symbolic_used_the_fact_B_is_symmetric = PETSC_TRUE;
922: }
924: switch (ptype) {
925: case MATPRODUCT_AB:
926: transA = false;
927: transB = false;
928: PetscCall(MatSetBlockSizesFromMats(C, A, B));
929: break;
930: case MATPRODUCT_AtB:
931: transA = true;
932: transB = false;
933: if (A->cmap->bs > 0) PetscCall(PetscLayoutSetBlockSize(C->rmap, A->cmap->bs));
934: if (B->cmap->bs > 0) PetscCall(PetscLayoutSetBlockSize(C->cmap, B->cmap->bs));
935: break;
936: case MATPRODUCT_ABt:
937: transA = false;
938: transB = true;
939: if (A->rmap->bs > 0) PetscCall(PetscLayoutSetBlockSize(C->rmap, A->rmap->bs));
940: if (B->rmap->bs > 0) PetscCall(PetscLayoutSetBlockSize(C->cmap, B->rmap->bs));
941: break;
942: default:
943: SETERRQ(comm, PETSC_ERR_PLIB, "Unsupported product type %s", MatProductTypes[product->type]);
944: }
945: PetscCallCXX(product->data = pdata = new MatProductCtx_SeqAIJKokkos());
946: pdata->reusesym = product->api_user;
948: /* TODO: add command line options to select spgemm algorithms */
949: auto spgemm_alg = KokkosSparse::SPGEMMAlgorithm::SPGEMM_DEFAULT; /* default alg is TPL if enabled, otherwise KK */
951: /* CUDA-10.2's spgemm has bugs. We prefer the SpGEMMreuse APIs introduced in cuda-11.4 */
952: #if defined(KOKKOSKERNELS_ENABLE_TPL_CUSPARSE)
953: #if PETSC_PKG_CUDA_VERSION_LT(11, 4, 0)
954: spgemm_alg = KokkosSparse::SPGEMMAlgorithm::SPGEMM_KK;
955: #endif
956: #endif
957: PetscCallCXX(pdata->kh.create_spgemm_handle(spgemm_alg));
959: PetscCall(PetscLogGpuTimeBegin());
960: /* TODO: Get rid of the explicit transpose once KK-spgemm implements the transpose option */
961: if (transA) {
962: PetscCall(MatSeqAIJKokkosGenerateTranspose_Private(A, &csrmatA));
963: transA = false;
964: }
966: if (transB) {
967: PetscCall(MatSeqAIJKokkosGenerateTranspose_Private(B, &csrmatB));
968: transB = false;
969: }
971: PetscCallCXX(KokkosSparse::spgemm_symbolic(pdata->kh, csrmatA, transA, csrmatB, transB, csrmatC));
972: /* spgemm_symbolic() only populates C's rowmap, but not C's column indices.
973: So we have to do a fake spgemm_numeric() here to get csrmatC.j_d setup, before
974: calling new Mat_SeqAIJKokkos().
975: TODO: Remove the fake spgemm_numeric() after KK fixed this problem.
976: */
977: PetscCallCXX(KokkosSparse::spgemm_numeric(pdata->kh, csrmatA, transA, csrmatB, transB, csrmatC));
978: #if PETSC_PKG_KOKKOS_KERNELS_VERSION_LT(4, 0, 0)
979: /* Query if KK outputs a sorted matrix. If not, we need to sort it */
980: auto spgemmHandle = pdata->kh.get_spgemm_handle();
981: if (spgemmHandle->get_sort_option() != 1) PetscCallCXX(sort_crs_matrix(csrmatC)); /* sort_option defaults to -1 in KK!*/
982: #endif
983: PetscCall(PetscLogGpuTimeEnd());
985: PetscCallCXX(ckok = new Mat_SeqAIJKokkos(csrmatC));
986: PetscCall(MatSetSeqAIJKokkosWithCSRMatrix(C, ckok));
987: C->product->destroy = MatProductCtxDestroy_SeqAIJKokkos;
988: PetscFunctionReturn(PETSC_SUCCESS);
989: }
991: /* handles sparse matrix matrix ops */
992: static PetscErrorCode MatProductSetFromOptions_SeqAIJKokkos(Mat mat)
993: {
994: Mat_Product *product = mat->product;
995: PetscBool Biskok = PETSC_FALSE, Ciskok = PETSC_TRUE;
997: PetscFunctionBegin;
998: MatCheckProduct(mat, 1);
999: PetscCall(PetscObjectTypeCompare((PetscObject)product->B, MATSEQAIJKOKKOS, &Biskok));
1000: if (product->type == MATPRODUCT_ABC) PetscCall(PetscObjectTypeCompare((PetscObject)product->C, MATSEQAIJKOKKOS, &Ciskok));
1001: if (Biskok && Ciskok) {
1002: switch (product->type) {
1003: case MATPRODUCT_AB:
1004: case MATPRODUCT_AtB:
1005: case MATPRODUCT_ABt:
1006: mat->ops->productsymbolic = MatProductSymbolic_SeqAIJKokkos_SeqAIJKokkos;
1007: break;
1008: case MATPRODUCT_PtAP:
1009: case MATPRODUCT_RARt:
1010: case MATPRODUCT_ABC:
1011: mat->ops->productsymbolic = MatProductSymbolic_ABC_Basic;
1012: break;
1013: default:
1014: break;
1015: }
1016: } else { /* fallback for AIJ */
1017: PetscCall(MatProductSetFromOptions_SeqAIJ(mat));
1018: }
1019: PetscFunctionReturn(PETSC_SUCCESS);
1020: }
1022: static PetscErrorCode MatScale_SeqAIJKokkos(Mat A, PetscScalar a)
1023: {
1024: Mat_SeqAIJKokkos *aijkok;
1026: PetscFunctionBegin;
1027: PetscCall(PetscLogGpuTimeBegin());
1028: PetscCall(MatSeqAIJKokkosSyncDevice(A));
1029: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1030: KokkosBlas::scal(PetscGetKokkosExecutionSpace(), aijkok->a_dual.view_device(), a, aijkok->a_dual.view_device());
1031: PetscCall(MatSeqAIJKokkosModifyDevice(A));
1032: PetscCall(PetscLogGpuFlops(aijkok->a_dual.extent(0)));
1033: PetscCall(PetscLogGpuTimeEnd());
1034: PetscFunctionReturn(PETSC_SUCCESS);
1035: }
1037: // add a to A's diagonal (if A is square) or main diagonal (if A is rectangular)
1038: static PetscErrorCode MatShift_SeqAIJKokkos(Mat A, PetscScalar a)
1039: {
1040: Mat_SeqAIJ *aijseq = static_cast<Mat_SeqAIJ *>(A->data);
1042: PetscFunctionBegin;
1043: if (A->assembled && aijseq->diagDense) { // no missing diagonals
1044: PetscInt n = PetscMin(A->rmap->n, A->cmap->n);
1046: PetscCall(PetscLogGpuTimeBegin());
1047: PetscCall(MatSeqAIJKokkosSyncDevice(A));
1048: const auto aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1049: const auto &Aa = aijkok->a_dual.view_device();
1050: const auto &Adiag = aijkok->diag_dual.view_device();
1051: PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, n), KOKKOS_LAMBDA(const PetscInt i) { Aa(Adiag(i)) += a; }));
1052: PetscCall(MatSeqAIJKokkosModifyDevice(A));
1053: PetscCall(PetscLogGpuFlops(n));
1054: PetscCall(PetscLogGpuTimeEnd());
1055: } else { // need reassembly, very slow!
1056: PetscCall(MatShift_Basic(A, a));
1057: }
1058: PetscFunctionReturn(PETSC_SUCCESS);
1059: }
1061: static PetscErrorCode MatDiagonalSet_SeqAIJKokkos(Mat Y, Vec D, InsertMode is)
1062: {
1063: Mat_SeqAIJ *aijseq = static_cast<Mat_SeqAIJ *>(Y->data);
1065: PetscFunctionBegin;
1066: if (Y->assembled && aijseq->diagDense) { // no missing diagonals
1067: ConstPetscScalarKokkosView dv;
1068: PetscInt n, nv;
1070: PetscCall(PetscLogGpuTimeBegin());
1071: PetscCall(MatSeqAIJKokkosSyncDevice(Y));
1072: PetscCall(VecGetKokkosView(D, &dv));
1073: PetscCall(VecGetLocalSize(D, &nv));
1074: n = PetscMin(Y->rmap->n, Y->cmap->n);
1075: PetscCheck(n == nv, PetscObjectComm((PetscObject)Y), PETSC_ERR_ARG_SIZ, "Matrix size and vector size do not match");
1077: const auto aijkok = static_cast<Mat_SeqAIJKokkos *>(Y->spptr);
1078: const auto &Aa = aijkok->a_dual.view_device();
1079: const auto &Adiag = aijkok->diag_dual.view_device();
1080: PetscCallCXX(Kokkos::parallel_for(
1081: Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, n), KOKKOS_LAMBDA(const PetscInt i) {
1082: if (is == INSERT_VALUES) Aa(Adiag(i)) = dv(i);
1083: else Aa(Adiag(i)) += dv(i);
1084: }));
1085: PetscCall(VecRestoreKokkosView(D, &dv));
1086: PetscCall(MatSeqAIJKokkosModifyDevice(Y));
1087: PetscCall(PetscLogGpuFlops(n));
1088: PetscCall(PetscLogGpuTimeEnd());
1089: } else { // need reassembly, very slow!
1090: PetscCall(MatDiagonalSet_Default(Y, D, is));
1091: }
1092: PetscFunctionReturn(PETSC_SUCCESS);
1093: }
1095: static PetscErrorCode MatDiagonalScale_SeqAIJKokkos(Mat A, Vec ll, Vec rr)
1096: {
1097: Mat_SeqAIJ *aijseq = static_cast<Mat_SeqAIJ *>(A->data);
1098: PetscInt m = A->rmap->n, n = A->cmap->n, nz = aijseq->nz;
1099: ConstPetscScalarKokkosView lv, rv;
1101: PetscFunctionBegin;
1102: PetscCall(PetscLogGpuTimeBegin());
1103: PetscCall(MatSeqAIJKokkosSyncDevice(A));
1104: const auto aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1105: const auto &Aa = aijkok->a_dual.view_device();
1106: const auto &Ai = aijkok->i_dual.view_device();
1107: const auto &Aj = aijkok->j_dual.view_device();
1108: if (ll) {
1109: PetscCall(VecGetLocalSize(ll, &m));
1110: PetscCheck(m == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Left scaling vector wrong length");
1111: PetscCall(VecGetKokkosView(ll, &lv));
1112: PetscCallCXX(Kokkos::parallel_for( // for each row
1113: Kokkos::TeamPolicy<>(PetscGetKokkosExecutionSpace(), m, Kokkos::AUTO()), KOKKOS_LAMBDA(const KokkosTeamMemberType &t) {
1114: PetscInt i = t.league_rank(); // row i
1115: PetscInt len = Ai(i + 1) - Ai(i);
1116: // scale entries on the row
1117: Kokkos::parallel_for(Kokkos::TeamThreadRange(t, len), [&](PetscInt j) { Aa(Ai(i) + j) *= lv(i); });
1118: }));
1119: PetscCall(VecRestoreKokkosView(ll, &lv));
1120: PetscCall(PetscLogGpuFlops(nz));
1121: }
1122: if (rr) {
1123: PetscCall(VecGetLocalSize(rr, &n));
1124: PetscCheck(n == A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Right scaling vector wrong length");
1125: PetscCall(VecGetKokkosView(rr, &rv));
1126: PetscCallCXX(Kokkos::parallel_for( // for each nonzero
1127: Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, nz), KOKKOS_LAMBDA(const PetscInt k) { Aa(k) *= rv(Aj(k)); }));
1128: PetscCall(VecRestoreKokkosView(rr, &lv));
1129: PetscCall(PetscLogGpuFlops(nz));
1130: }
1131: PetscCall(MatSeqAIJKokkosModifyDevice(A));
1132: PetscCall(PetscLogGpuTimeEnd());
1133: PetscFunctionReturn(PETSC_SUCCESS);
1134: }
1136: static PetscErrorCode MatZeroEntries_SeqAIJKokkos(Mat A)
1137: {
1138: Mat_SeqAIJKokkos *aijkok;
1140: PetscFunctionBegin;
1141: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1142: if (aijkok) { /* Only zero the device if data is already there */
1143: KokkosBlas::fill(PetscGetKokkosExecutionSpace(), aijkok->a_dual.view_device(), 0.0);
1144: PetscCall(MatSeqAIJKokkosModifyDevice(A));
1145: } else { /* Might be preallocated but not assembled */
1146: PetscCall(MatZeroEntries_SeqAIJ(A));
1147: }
1148: PetscFunctionReturn(PETSC_SUCCESS);
1149: }
1151: static PetscErrorCode MatGetDiagonal_SeqAIJKokkos(Mat A, Vec x)
1152: {
1153: Mat_SeqAIJKokkos *aijkok;
1154: PetscInt n;
1155: PetscScalarKokkosView xv;
1157: PetscFunctionBegin;
1158: PetscCall(VecGetLocalSize(x, &n));
1159: PetscCheck(n == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nonconforming matrix and vector");
1160: PetscCheck(A->factortype == MAT_FACTOR_NONE, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatGetDiagonal_SeqAIJKokkos not supported on factored matrices");
1162: PetscCall(MatSeqAIJKokkosSyncDevice(A));
1163: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1165: const auto &Aa = aijkok->a_dual.view_device();
1166: const auto &Ai = aijkok->i_dual.view_device();
1167: const auto &Adiag = aijkok->diag_dual.view_device();
1169: PetscCall(VecGetKokkosViewWrite(x, &xv));
1170: Kokkos::parallel_for(
1171: Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, n), KOKKOS_LAMBDA(const PetscInt i) {
1172: if (Adiag(i) < Ai(i + 1)) xv(i) = Aa(Adiag(i));
1173: else xv(i) = 0;
1174: });
1175: PetscCall(VecRestoreKokkosViewWrite(x, &xv));
1176: PetscFunctionReturn(PETSC_SUCCESS);
1177: }
1179: /* Get a Kokkos View from a mat of type MatSeqAIJKokkos */
1180: PetscErrorCode MatSeqAIJGetKokkosView(Mat A, ConstMatScalarKokkosView *kv)
1181: {
1182: Mat_SeqAIJKokkos *aijkok;
1184: PetscFunctionBegin;
1186: PetscAssertPointer(kv, 2);
1187: PetscCheckTypeName(A, MATSEQAIJKOKKOS);
1188: PetscCall(MatSeqAIJKokkosSyncDevice(A));
1189: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1190: *kv = aijkok->a_dual.view_device();
1191: PetscFunctionReturn(PETSC_SUCCESS);
1192: }
1194: PetscErrorCode MatSeqAIJRestoreKokkosView(Mat A, ConstMatScalarKokkosView *kv)
1195: {
1196: PetscFunctionBegin;
1198: PetscAssertPointer(kv, 2);
1199: PetscCheckTypeName(A, MATSEQAIJKOKKOS);
1200: PetscFunctionReturn(PETSC_SUCCESS);
1201: }
1203: PetscErrorCode MatSeqAIJGetKokkosView(Mat A, MatScalarKokkosView *kv)
1204: {
1205: Mat_SeqAIJKokkos *aijkok;
1207: PetscFunctionBegin;
1209: PetscAssertPointer(kv, 2);
1210: PetscCheckTypeName(A, MATSEQAIJKOKKOS);
1211: PetscCall(MatSeqAIJKokkosSyncDevice(A));
1212: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1213: *kv = aijkok->a_dual.view_device();
1214: PetscFunctionReturn(PETSC_SUCCESS);
1215: }
1217: PetscErrorCode MatSeqAIJRestoreKokkosView(Mat A, MatScalarKokkosView *kv)
1218: {
1219: PetscFunctionBegin;
1221: PetscAssertPointer(kv, 2);
1222: PetscCheckTypeName(A, MATSEQAIJKOKKOS);
1223: PetscCall(MatSeqAIJKokkosModifyDevice(A));
1224: PetscFunctionReturn(PETSC_SUCCESS);
1225: }
1227: PetscErrorCode MatSeqAIJGetKokkosViewWrite(Mat A, MatScalarKokkosView *kv)
1228: {
1229: Mat_SeqAIJKokkos *aijkok;
1231: PetscFunctionBegin;
1233: PetscAssertPointer(kv, 2);
1234: PetscCheckTypeName(A, MATSEQAIJKOKKOS);
1235: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1236: *kv = aijkok->a_dual.view_device();
1237: PetscFunctionReturn(PETSC_SUCCESS);
1238: }
1240: PetscErrorCode MatSeqAIJRestoreKokkosViewWrite(Mat A, MatScalarKokkosView *kv)
1241: {
1242: PetscFunctionBegin;
1244: PetscAssertPointer(kv, 2);
1245: PetscCheckTypeName(A, MATSEQAIJKOKKOS);
1246: PetscCall(MatSeqAIJKokkosModifyDevice(A));
1247: PetscFunctionReturn(PETSC_SUCCESS);
1248: }
1250: PetscErrorCode MatCreateSeqAIJKokkosWithKokkosViews(MPI_Comm comm, PetscInt m, PetscInt n, Kokkos::View<PetscInt *> &i_d, Kokkos::View<PetscInt *> &j_d, Kokkos::View<PetscScalar *> &a_d, Mat *A)
1251: {
1252: Mat_SeqAIJKokkos *akok;
1254: PetscFunctionBegin;
1255: PetscCallCXX(akok = new Mat_SeqAIJKokkos(m, n, j_d.extent(0), i_d, j_d, a_d));
1256: PetscCall(MatCreate(comm, A));
1257: PetscCall(MatSetSeqAIJKokkosWithCSRMatrix(*A, akok));
1258: PetscFunctionReturn(PETSC_SUCCESS);
1259: }
1261: /* Computes Y += alpha X */
1262: static PetscErrorCode MatAXPY_SeqAIJKokkos(Mat Y, PetscScalar alpha, Mat X, MatStructure pattern)
1263: {
1264: Mat_SeqAIJ *x = (Mat_SeqAIJ *)X->data, *y = (Mat_SeqAIJ *)Y->data;
1265: Mat_SeqAIJKokkos *xkok, *ykok, *zkok;
1266: ConstMatScalarKokkosView Xa;
1267: MatScalarKokkosView Ya;
1268: auto exec = PetscGetKokkosExecutionSpace();
1270: PetscFunctionBegin;
1271: PetscCheckTypeName(Y, MATSEQAIJKOKKOS);
1272: PetscCheckTypeName(X, MATSEQAIJKOKKOS);
1273: PetscCall(MatSeqAIJKokkosSyncDevice(Y));
1274: PetscCall(MatSeqAIJKokkosSyncDevice(X));
1275: PetscCall(PetscLogGpuTimeBegin());
1277: if (pattern != SAME_NONZERO_PATTERN && x->nz == y->nz) {
1278: PetscBool e;
1279: PetscCall(PetscArraycmp(x->i, y->i, Y->rmap->n + 1, &e));
1280: if (e) {
1281: PetscCall(PetscArraycmp(x->j, y->j, y->nz, &e));
1282: if (e) pattern = SAME_NONZERO_PATTERN;
1283: }
1284: }
1286: /* cusparseDcsrgeam2() computes C = alpha A + beta B. If one knew sparsity pattern of C, one can skip
1287: cusparseScsrgeam2_bufferSizeExt() / cusparseXcsrgeam2Nnz(), and directly call cusparseScsrgeam2().
1288: If X is SUBSET_NONZERO_PATTERN of Y, we could take advantage of this cusparse feature. However,
1289: KokkosSparse::spadd(alpha,A,beta,B,C) has symbolic and numeric phases, MatAXPY does not.
1290: */
1291: ykok = static_cast<Mat_SeqAIJKokkos *>(Y->spptr);
1292: xkok = static_cast<Mat_SeqAIJKokkos *>(X->spptr);
1293: Xa = xkok->a_dual.view_device();
1294: Ya = ykok->a_dual.view_device();
1296: if (pattern == SAME_NONZERO_PATTERN) {
1297: KokkosBlas::axpy(exec, alpha, Xa, Ya);
1298: PetscCall(MatSeqAIJKokkosModifyDevice(Y));
1299: } else if (pattern == SUBSET_NONZERO_PATTERN) {
1300: MatRowMapKokkosView Xi = xkok->i_dual.view_device(), Yi = ykok->i_dual.view_device();
1301: MatColIdxKokkosView Xj = xkok->j_dual.view_device(), Yj = ykok->j_dual.view_device();
1303: Kokkos::parallel_for(
1304: Kokkos::TeamPolicy<>(exec, Y->rmap->n, 1), KOKKOS_LAMBDA(const KokkosTeamMemberType &t) {
1305: PetscInt i = t.league_rank(); // row i
1306: Kokkos::single(Kokkos::PerTeam(t), [=]() {
1307: // Only one thread works in a team
1308: PetscInt p, q = Yi(i);
1309: for (p = Xi(i); p < Xi(i + 1); p++) { // For each nonzero on row i of X,
1310: while (Xj(p) != Yj(q) && q < Yi(i + 1)) q++; // find the matching nonzero on row i of Y.
1311: if (Xj(p) == Yj(q)) { // Found it
1312: Ya(q) += alpha * Xa(p);
1313: q++;
1314: } else {
1315: // If not found, it indicates the input is wrong (X is not a SUBSET_NONZERO_PATTERN of Y).
1316: // Just insert a NaN at the beginning of row i if it is not empty, to make the result wrong.
1317: #if PETSC_PKG_KOKKOS_VERSION_GE(5, 0, 0)
1318: if (Yi(i) != Yi(i + 1)) Ya(Yi(i)) = KokkosKernels::ArithTraits<PetscScalar>::nan();
1319: #elif PETSC_PKG_KOKKOS_VERSION_GE(3, 7, 0)
1320: if (Yi(i) != Yi(i + 1)) Ya(Yi(i)) = Kokkos::ArithTraits<PetscScalar>::nan();
1321: #else
1322: if (Yi(i) != Yi(i + 1)) Ya(Yi(i)) = Kokkos::Experimental::nan("1");
1323: #endif
1324: }
1325: }
1326: });
1327: });
1328: PetscCall(MatSeqAIJKokkosModifyDevice(Y));
1329: } else { // different nonzero patterns
1330: Mat Z;
1331: KokkosCsrMatrix zcsr;
1332: KernelHandle kh;
1333: kh.create_spadd_handle(true); // X, Y are sorted
1334: KokkosSparse::spadd_symbolic(&kh, xkok->csrmat, ykok->csrmat, zcsr);
1335: KokkosSparse::spadd_numeric(&kh, alpha, xkok->csrmat, (PetscScalar)1.0, ykok->csrmat, zcsr);
1336: zkok = new Mat_SeqAIJKokkos(zcsr);
1337: PetscCall(MatCreateSeqAIJKokkosWithCSRMatrix(PETSC_COMM_SELF, zkok, &Z));
1338: PetscCall(MatHeaderReplace(Y, &Z));
1339: kh.destroy_spadd_handle();
1340: }
1341: PetscCall(PetscLogGpuTimeEnd());
1342: PetscCall(PetscLogGpuFlops(xkok->a_dual.extent(0) * 2)); // Because we scaled X and then added it to Y
1343: PetscFunctionReturn(PETSC_SUCCESS);
1344: }
1346: struct MatCOOStruct_SeqAIJKokkos {
1347: PetscCount n;
1348: PetscCount Atot;
1349: PetscInt nz;
1350: PetscCountKokkosView jmap;
1351: PetscCountKokkosView perm;
1353: MatCOOStruct_SeqAIJKokkos(const MatCOOStruct_SeqAIJ *coo_h)
1354: {
1355: nz = coo_h->nz;
1356: n = coo_h->n;
1357: Atot = coo_h->Atot;
1358: jmap = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), PetscCountKokkosViewHost(coo_h->jmap, nz + 1));
1359: perm = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), PetscCountKokkosViewHost(coo_h->perm, Atot));
1360: }
1361: };
1363: static PetscErrorCode MatCOOStructDestroy_SeqAIJKokkos(PetscCtxRt data)
1364: {
1365: PetscFunctionBegin;
1366: PetscCallCXX(delete *static_cast<MatCOOStruct_SeqAIJKokkos **>(data));
1367: PetscFunctionReturn(PETSC_SUCCESS);
1368: }
1370: static PetscErrorCode MatSetPreallocationCOO_SeqAIJKokkos(Mat mat, PetscCount coo_n, PetscInt coo_i[], PetscInt coo_j[])
1371: {
1372: Mat_SeqAIJKokkos *akok;
1373: Mat_SeqAIJ *aseq;
1374: PetscContainer container_h;
1375: MatCOOStruct_SeqAIJ *coo_h;
1376: MatCOOStruct_SeqAIJKokkos *coo_d;
1378: PetscFunctionBegin;
1379: PetscCall(MatSetPreallocationCOO_SeqAIJ(mat, coo_n, coo_i, coo_j));
1380: aseq = static_cast<Mat_SeqAIJ *>(mat->data);
1381: akok = static_cast<Mat_SeqAIJKokkos *>(mat->spptr);
1382: delete akok;
1383: mat->spptr = akok = new Mat_SeqAIJKokkos(mat, mat->rmap->n, mat->cmap->n, aseq, mat->nonzerostate + 1, PETSC_FALSE);
1384: PetscCall(MatZeroEntries_SeqAIJKokkos(mat));
1386: // Copy the COO struct to device
1387: PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", (PetscObject *)&container_h));
1388: PetscCall(PetscContainerGetPointer(container_h, &coo_h));
1389: PetscCallCXX(coo_d = new MatCOOStruct_SeqAIJKokkos(coo_h));
1391: // Put the COO struct in a container and then attach that to the matrix
1392: PetscCall(PetscObjectContainerCompose((PetscObject)mat, "__PETSc_MatCOOStruct_Device", coo_d, MatCOOStructDestroy_SeqAIJKokkos));
1393: PetscFunctionReturn(PETSC_SUCCESS);
1394: }
1396: static PetscErrorCode MatSetValuesCOO_SeqAIJKokkos(Mat A, const PetscScalar v[], InsertMode imode)
1397: {
1398: MatScalarKokkosView Aa;
1399: ConstMatScalarKokkosView kv;
1400: PetscMemType memtype;
1401: PetscContainer container;
1402: MatCOOStruct_SeqAIJKokkos *coo;
1404: PetscFunctionBegin;
1405: PetscCall(PetscObjectQuery((PetscObject)A, "__PETSc_MatCOOStruct_Device", (PetscObject *)&container));
1406: PetscCall(PetscContainerGetPointer(container, &coo));
1408: const auto &n = coo->n;
1409: const auto &Annz = coo->nz;
1410: const auto &jmap = coo->jmap;
1411: const auto &perm = coo->perm;
1413: PetscCall(PetscGetMemType(v, &memtype));
1414: if (PetscMemTypeHost(memtype)) { /* If user gave v[] in host, we might need to copy it to device if any */
1415: kv = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), ConstMatScalarKokkosViewHost(v, n));
1416: } else {
1417: kv = ConstMatScalarKokkosView(v, n); /* Directly use v[]'s memory */
1418: }
1420: if (imode == INSERT_VALUES) PetscCall(MatSeqAIJGetKokkosViewWrite(A, &Aa)); /* write matrix values */
1421: else PetscCall(MatSeqAIJGetKokkosView(A, &Aa)); /* read & write matrix values */
1423: PetscCall(PetscLogGpuTimeBegin());
1424: Kokkos::parallel_for(
1425: Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, Annz), KOKKOS_LAMBDA(const PetscCount i) {
1426: PetscScalar sum = 0.0;
1427: for (PetscCount k = jmap(i); k < jmap(i + 1); k++) sum += kv(perm(k));
1428: Aa(i) = (imode == INSERT_VALUES ? 0.0 : Aa(i)) + sum;
1429: });
1430: PetscCall(PetscLogGpuTimeEnd());
1432: if (imode == INSERT_VALUES) PetscCall(MatSeqAIJRestoreKokkosViewWrite(A, &Aa));
1433: else PetscCall(MatSeqAIJRestoreKokkosView(A, &Aa));
1434: PetscFunctionReturn(PETSC_SUCCESS);
1435: }
1437: PETSC_INTERN PetscErrorCode MatBindToCPU_SeqAIJKokkos(Mat A, PetscBool flg)
1438: {
1439: PetscFunctionBegin;
1440: PetscCheck(A->boundtocpu == flg, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Changing binding of a MATAIJKOKKOS matrix is not supported yet");
1441: PetscFunctionReturn(PETSC_SUCCESS);
1442: }
1444: static PetscErrorCode MatSetOps_SeqAIJKokkos(Mat A)
1445: {
1446: Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
1448: PetscFunctionBegin;
1449: A->offloadmask = PETSC_OFFLOAD_KOKKOS; // We do not really use this flag
1450: A->boundtocpu = PetscDefined(HAVE_KOKKOS_WITHOUT_GPU) ? PETSC_TRUE : PETSC_FALSE; // MATAIJKOKKOS has yet to support CPU binding. But in this case, we deem it is bound to CPU.
1451: A->ops->assemblyend = MatAssemblyEnd_SeqAIJKokkos;
1452: A->ops->destroy = MatDestroy_SeqAIJKokkos;
1453: A->ops->duplicate = MatDuplicate_SeqAIJKokkos;
1454: A->ops->axpy = MatAXPY_SeqAIJKokkos;
1455: A->ops->scale = MatScale_SeqAIJKokkos;
1456: A->ops->zeroentries = MatZeroEntries_SeqAIJKokkos;
1457: A->ops->productsetfromoptions = MatProductSetFromOptions_SeqAIJKokkos;
1458: A->ops->mult = MatMult_SeqAIJKokkos;
1459: A->ops->multadd = MatMultAdd_SeqAIJKokkos;
1460: A->ops->multtranspose = MatMultTranspose_SeqAIJKokkos;
1461: A->ops->multtransposeadd = MatMultTransposeAdd_SeqAIJKokkos;
1462: A->ops->multhermitiantranspose = MatMultHermitianTranspose_SeqAIJKokkos;
1463: A->ops->multhermitiantransposeadd = MatMultHermitianTransposeAdd_SeqAIJKokkos;
1464: A->ops->productnumeric = MatProductNumeric_SeqAIJKokkos_SeqAIJKokkos;
1465: A->ops->transpose = MatTranspose_SeqAIJKokkos;
1466: A->ops->setoption = MatSetOption_SeqAIJKokkos;
1467: A->ops->getdiagonal = MatGetDiagonal_SeqAIJKokkos;
1468: A->ops->shift = MatShift_SeqAIJKokkos;
1469: A->ops->diagonalset = MatDiagonalSet_SeqAIJKokkos;
1470: A->ops->diagonalscale = MatDiagonalScale_SeqAIJKokkos;
1471: A->ops->getcurrentmemtype = MatGetCurrentMemType_SeqAIJKokkos;
1472: A->ops->bindtocpu = MatBindToCPU_SeqAIJKokkos;
1473: a->ops->getarray = MatSeqAIJGetArray_SeqAIJKokkos;
1474: a->ops->restorearray = MatSeqAIJRestoreArray_SeqAIJKokkos;
1475: a->ops->getarrayread = MatSeqAIJGetArrayRead_SeqAIJKokkos;
1476: a->ops->restorearrayread = MatSeqAIJRestoreArrayRead_SeqAIJKokkos;
1477: a->ops->getarraywrite = MatSeqAIJGetArrayWrite_SeqAIJKokkos;
1478: a->ops->restorearraywrite = MatSeqAIJRestoreArrayWrite_SeqAIJKokkos;
1479: a->ops->getcsrandmemtype = MatSeqAIJGetCSRAndMemType_SeqAIJKokkos;
1481: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSetPreallocationCOO_C", MatSetPreallocationCOO_SeqAIJKokkos));
1482: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSetValuesCOO_C", MatSetValuesCOO_SeqAIJKokkos));
1483: #if defined(PETSC_HAVE_HYPRE)
1484: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaijkokkos_hypre_C", MatConvert_AIJ_HYPRE));
1485: #endif
1486: PetscFunctionReturn(PETSC_SUCCESS);
1487: }
1489: /*
1490: Extract the (prescribled) diagonal blocks of the matrix and then invert them
1492: Input Parameters:
1493: + A - the MATSEQAIJKOKKOS matrix
1494: . bs - block sizes in 'csr' format, i.e., the i-th block has size bs(i+1) - bs(i)
1495: . bs2 - square of block sizes in 'csr' format, i.e., the i-th block should be stored at offset bs2(i) in diagVal[]
1496: . blkMap - map row ids to block ids, i.e., row i belongs to the block blkMap(i)
1497: - work - a pre-allocated work buffer (as big as diagVal) for use by this routine
1499: Output Parameter:
1500: . diagVal - the (pre-allocated) buffer to store the inverted blocks (each block is stored in column-major order)
1501: */
1502: PETSC_INTERN PetscErrorCode MatInvertVariableBlockDiagonal_SeqAIJKokkos(Mat A, const PetscIntKokkosView &bs, const PetscIntKokkosView &bs2, const PetscIntKokkosView &blkMap, PetscScalarKokkosView &work, PetscScalarKokkosView &diagVal)
1503: {
1504: Mat_SeqAIJKokkos *akok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1505: PetscInt nblocks = bs.extent(0) - 1;
1507: PetscFunctionBegin;
1508: PetscCall(MatSeqAIJKokkosSyncDevice(A)); // Since we'll access A's value on device
1510: // Pull out the diagonal blocks of the matrix and then invert the blocks
1511: auto Aa = akok->a_dual.view_device();
1512: auto Ai = akok->i_dual.view_device();
1513: auto Aj = akok->j_dual.view_device();
1514: auto Adiag = akok->diag_dual.view_device();
1515: // TODO: how to tune the team size?
1516: #if defined(KOKKOS_ENABLE_UNIFIED_MEMORY)
1517: auto ts = Kokkos::AUTO();
1518: #else
1519: auto ts = 16; // improved performance 30% over Kokkos::AUTO() with CUDA, but failed with "Kokkos::abort: Requested Team Size is too large!" on CPUs
1520: #endif
1521: PetscCallCXX(Kokkos::parallel_for(
1522: Kokkos::TeamPolicy<>(PetscGetKokkosExecutionSpace(), nblocks, ts), KOKKOS_LAMBDA(const KokkosTeamMemberType &teamMember) {
1523: const PetscInt bid = teamMember.league_rank(); // block id
1524: const PetscInt rstart = bs(bid); // this block starts from this row
1525: const PetscInt m = bs(bid + 1) - bs(bid); // size of this block
1526: const auto &B = Kokkos::View<PetscScalar **, Kokkos::LayoutLeft>(&diagVal(bs2(bid)), m, m); // column-major order
1527: const auto &W = PetscScalarKokkosView(&work(bs2(bid)), m * m);
1529: Kokkos::parallel_for(Kokkos::TeamThreadRange(teamMember, m), [=](const PetscInt &r) { // r-th row in B
1530: PetscInt i = rstart + r; // i-th row in A
1532: if (Ai(i) <= Adiag(i) && Adiag(i) < Ai(i + 1)) { // if the diagonal exists (common case)
1533: PetscInt first = Adiag(i) - r; // we start to check nonzeros from here along this row
1535: for (PetscInt c = 0; c < m; c++) { // walk n steps to see what column indices we will meet
1536: if (first + c < Ai(i) || first + c >= Ai(i + 1)) { // this entry (first+c) is out of range of this row, in other words, its value is zero
1537: B(r, c) = 0.0;
1538: } else if (Aj(first + c) == rstart + c) { // this entry is right on the (rstart+c) column
1539: B(r, c) = Aa(first + c);
1540: } else { // this entry does not show up in the CSR
1541: B(r, c) = 0.0;
1542: }
1543: }
1544: } else { // rare case that the diagonal does not exist
1545: const PetscInt begin = Ai(i);
1546: const PetscInt end = Ai(i + 1);
1547: for (PetscInt c = 0; c < m; c++) B(r, c) = 0.0;
1548: for (PetscInt j = begin; j < end; j++) { // scan the whole row; could use binary search but this is a rare case so we did not.
1549: if (rstart <= Aj(j) && Aj(j) < rstart + m) B(r, Aj(j) - rstart) = Aa(j);
1550: else if (Aj(j) >= rstart + m) break;
1551: }
1552: }
1553: });
1555: // LU-decompose B (w/o pivoting) and then invert B
1556: KokkosBatched::TeamLU<KokkosTeamMemberType, KokkosBatched::Algo::LU::Unblocked>::invoke(teamMember, B, 0.0);
1557: KokkosBatched::TeamInverseLU<KokkosTeamMemberType, KokkosBatched::Algo::InverseLU::Unblocked>::invoke(teamMember, B, W);
1558: }));
1559: // PetscLogGpuFlops() is done in the caller PCSetUp_VPBJacobi_Kokkos as we don't want to compute the flops in kernels
1560: PetscFunctionReturn(PETSC_SUCCESS);
1561: }
1563: PETSC_INTERN PetscErrorCode MatSetSeqAIJKokkosWithCSRMatrix(Mat A, Mat_SeqAIJKokkos *akok)
1564: {
1565: Mat_SeqAIJ *aseq;
1566: PetscInt i, m, n;
1567: auto exec = PetscGetKokkosExecutionSpace();
1569: PetscFunctionBegin;
1570: PetscCheck(!A->spptr, PETSC_COMM_SELF, PETSC_ERR_PLIB, "A->spptr is supposed to be empty");
1572: m = akok->nrows();
1573: n = akok->ncols();
1574: PetscCall(MatSetSizes(A, m, n, m, n));
1575: PetscCall(MatSetType(A, MATSEQAIJKOKKOS));
1577: /* Set up data structures of A as a MATSEQAIJ */
1578: PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(A, MAT_SKIP_ALLOCATION, NULL));
1579: aseq = (Mat_SeqAIJ *)A->data;
1581: PetscCall(KokkosDualViewSyncHost(akok->i_dual, exec)); /* We always need sync'ed i, j on host */
1582: PetscCall(KokkosDualViewSyncHost(akok->j_dual, exec));
1584: aseq->i = akok->i_host_data();
1585: aseq->j = akok->j_host_data();
1586: aseq->a = akok->a_host_data();
1587: aseq->nonew = -1; /*this indicates that inserting a new value in the matrix that generates a new nonzero is an error*/
1588: aseq->free_a = PETSC_FALSE;
1589: aseq->free_ij = PETSC_FALSE;
1590: aseq->nz = akok->nnz();
1591: aseq->maxnz = aseq->nz;
1593: PetscCall(PetscMalloc1(m, &aseq->imax));
1594: PetscCall(PetscMalloc1(m, &aseq->ilen));
1595: for (i = 0; i < m; i++) aseq->ilen[i] = aseq->imax[i] = aseq->i[i + 1] - aseq->i[i];
1597: /* It is critical to set the nonzerostate, as we use it to check if sparsity pattern (hence data) has changed on host in MatAssemblyEnd */
1598: akok->nonzerostate = A->nonzerostate;
1599: A->spptr = akok; /* Set A->spptr before MatAssembly so that A->spptr won't be allocated again there */
1600: PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
1601: PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
1602: PetscFunctionReturn(PETSC_SUCCESS);
1603: }
1605: PETSC_INTERN PetscErrorCode MatSeqAIJKokkosGetKokkosCsrMatrix(Mat A, KokkosCsrMatrix *csr)
1606: {
1607: PetscFunctionBegin;
1608: PetscCall(MatSeqAIJKokkosSyncDevice(A));
1609: *csr = static_cast<Mat_SeqAIJKokkos *>(A->spptr)->csrmat;
1610: PetscFunctionReturn(PETSC_SUCCESS);
1611: }
1613: PETSC_INTERN PetscErrorCode MatCreateSeqAIJKokkosWithKokkosCsrMatrix(MPI_Comm comm, KokkosCsrMatrix csr, Mat *A)
1614: {
1615: Mat_SeqAIJKokkos *akok;
1617: PetscFunctionBegin;
1618: PetscCallCXX(akok = new Mat_SeqAIJKokkos(csr));
1619: PetscCall(MatCreate(comm, A));
1620: PetscCall(MatSetSeqAIJKokkosWithCSRMatrix(*A, akok));
1621: PetscFunctionReturn(PETSC_SUCCESS);
1622: }
1624: /* Crete a SEQAIJKOKKOS matrix with a Mat_SeqAIJKokkos data structure
1626: Note we have names like MatSeqAIJSetPreallocationCSR, so I use capitalized CSR
1627: */
1628: PETSC_INTERN PetscErrorCode MatCreateSeqAIJKokkosWithCSRMatrix(MPI_Comm comm, Mat_SeqAIJKokkos *akok, Mat *A)
1629: {
1630: PetscFunctionBegin;
1631: PetscCall(MatCreate(comm, A));
1632: PetscCall(MatSetSeqAIJKokkosWithCSRMatrix(*A, akok));
1633: PetscFunctionReturn(PETSC_SUCCESS);
1634: }
1636: /*@C
1637: MatCreateSeqAIJKokkos - Creates a sparse matrix in `MATSEQAIJKOKKOS` (compressed row) format
1638: (the default parallel PETSc format). This matrix will ultimately be handled by
1639: Kokkos for calculations.
1641: Collective
1643: Input Parameters:
1644: + comm - MPI communicator, set to `PETSC_COMM_SELF`
1645: . m - number of rows
1646: . n - number of columns
1647: . nz - number of nonzeros per row (same for all rows), ignored if `nnz` is provided
1648: - nnz - array containing the number of nonzeros in the various rows (possibly different for each row) or `NULL`
1650: Output Parameter:
1651: . A - the matrix
1653: Level: intermediate
1655: Notes:
1656: It is recommended that one use the `MatCreate()`, `MatSetType()` and/or `MatSetFromOptions()`,
1657: MatXXXXSetPreallocation() paradgm instead of this routine directly.
1658: [MatXXXXSetPreallocation() is, for example, `MatSeqAIJSetPreallocation()`]
1660: The AIJ format, also called
1661: compressed row storage, is fully compatible with standard Fortran
1662: storage. That is, the stored row and column indices can begin at
1663: either one (as in Fortran) or zero.
1665: Specify the preallocated storage with either `nz` or `nnz` (not both).
1666: Set `nz` = `PETSC_DEFAULT` and `nnz` = `NULL` for PETSc to control dynamic memory
1667: allocation.
1669: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateAIJ()`, `MatSetValues()`, `MatSeqAIJSetColumnIndices()`, `MatCreateSeqAIJWithArrays()`
1670: @*/
1671: PetscErrorCode MatCreateSeqAIJKokkos(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt nz, const PetscInt nnz[], Mat *A)
1672: {
1673: PetscFunctionBegin;
1674: PetscCall(PetscKokkosInitializeCheck());
1675: PetscCall(MatCreate(comm, A));
1676: PetscCall(MatSetSizes(*A, m, n, m, n));
1677: PetscCall(MatSetType(*A, MATSEQAIJKOKKOS));
1678: PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(*A, nz, (PetscInt *)nnz));
1679: PetscFunctionReturn(PETSC_SUCCESS);
1680: }
1682: // After matrix numeric factorization, there are still steps to do before triangular solve can be called.
1683: // For example, for transpose solve, we might need to compute the transpose matrices if the solver does not support it (such as KK, while cusparse does).
1684: // In cusparse, one has to call cusparseSpSV_analysis() with updated triangular matrix values before calling cusparseSpSV_solve().
1685: // Simiarily, in KK sptrsv_symbolic() has to be called before sptrsv_solve(). We put these steps in MatSeqAIJKokkos{Transpose}SolveCheck.
1686: static PetscErrorCode MatSeqAIJKokkosSolveCheck(Mat A)
1687: {
1688: Mat_SeqAIJKokkosTriFactors *factors = (Mat_SeqAIJKokkosTriFactors *)A->spptr;
1689: const PetscBool has_lower = factors->iL_d.extent(0) ? PETSC_TRUE : PETSC_FALSE; // false with Choleksy
1690: const PetscBool has_upper = factors->iU_d.extent(0) ? PETSC_TRUE : PETSC_FALSE; // true with LU and Choleksy
1692: PetscFunctionBegin;
1693: if (!factors->sptrsv_symbolic_completed) { // If sptrsv_symbolic was not called yet
1694: if (has_upper) PetscCallCXX(sptrsv_symbolic(&factors->khU, factors->iU_d, factors->jU_d, factors->aU_d));
1695: if (has_lower) PetscCallCXX(sptrsv_symbolic(&factors->khL, factors->iL_d, factors->jL_d, factors->aL_d));
1696: factors->sptrsv_symbolic_completed = PETSC_TRUE;
1697: }
1698: PetscFunctionReturn(PETSC_SUCCESS);
1699: }
1701: static PetscErrorCode MatSeqAIJKokkosTransposeSolveCheck(Mat A)
1702: {
1703: const PetscInt n = A->rmap->n;
1704: Mat_SeqAIJKokkosTriFactors *factors = (Mat_SeqAIJKokkosTriFactors *)A->spptr;
1705: const PetscBool has_lower = factors->iL_d.extent(0) ? PETSC_TRUE : PETSC_FALSE; // false with Choleksy
1706: const PetscBool has_upper = factors->iU_d.extent(0) ? PETSC_TRUE : PETSC_FALSE; // true with LU or Choleksy
1708: PetscFunctionBegin;
1709: if (!factors->transpose_updated) {
1710: if (has_upper) {
1711: if (!factors->iUt_d.extent(0)) { // Allocate Ut on device if not yet
1712: factors->iUt_d = MatRowMapKokkosView("factors->iUt_d", n + 1); // KK requires this view to be initialized to 0 to call transpose_matrix
1713: factors->jUt_d = MatColIdxKokkosView(NoInit("factors->jUt_d"), factors->jU_d.extent(0));
1714: factors->aUt_d = MatScalarKokkosView(NoInit("factors->aUt_d"), factors->aU_d.extent(0));
1715: }
1717: if (factors->iU_h.extent(0)) { // If U is on host (factorization was done on host), we also compute the transpose on host
1718: if (!factors->U) {
1719: Mat_SeqAIJ *seq;
1721: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, n, n, factors->iU_h.data(), factors->jU_h.data(), factors->aU_h.data(), &factors->U));
1722: PetscCall(MatTranspose(factors->U, MAT_INITIAL_MATRIX, &factors->Ut));
1724: seq = static_cast<Mat_SeqAIJ *>(factors->Ut->data);
1725: factors->iUt_h = MatRowMapKokkosViewHost(seq->i, n + 1);
1726: factors->jUt_h = MatColIdxKokkosViewHost(seq->j, seq->nz);
1727: factors->aUt_h = MatScalarKokkosViewHost(seq->a, seq->nz);
1728: } else {
1729: PetscCall(MatTranspose(factors->U, MAT_REUSE_MATRIX, &factors->Ut)); // Matrix Ut' data is aliased with {i, j, a}Ut_h
1730: }
1731: // Copy Ut from host to device
1732: PetscCallCXX(Kokkos::deep_copy(factors->iUt_d, factors->iUt_h));
1733: PetscCallCXX(Kokkos::deep_copy(factors->jUt_d, factors->jUt_h));
1734: PetscCallCXX(Kokkos::deep_copy(factors->aUt_d, factors->aUt_h));
1735: } else { // If U was computed on device, we also compute the transpose there
1736: // TODO: KK transpose_matrix() does not sort column indices, however cusparse requires sorted indices. We have to sort the indices, until KK provides finer control options.
1737: PetscCallCXX(transpose_matrix<ConstMatRowMapKokkosView, ConstMatColIdxKokkosView, ConstMatScalarKokkosView, MatRowMapKokkosView, MatColIdxKokkosView, MatScalarKokkosView, MatRowMapKokkosView, DefaultExecutionSpace>(n, n, factors->iU_d,
1738: factors->jU_d, factors->aU_d,
1739: factors->iUt_d, factors->jUt_d,
1740: factors->aUt_d));
1741: PetscCallCXX(sort_crs_matrix<DefaultExecutionSpace, MatRowMapKokkosView, MatColIdxKokkosView, MatScalarKokkosView>(factors->iUt_d, factors->jUt_d, factors->aUt_d));
1742: }
1743: PetscCallCXX(sptrsv_symbolic(&factors->khUt, factors->iUt_d, factors->jUt_d, factors->aUt_d));
1744: }
1746: // do the same for L with LU
1747: if (has_lower) {
1748: if (!factors->iLt_d.extent(0)) { // Allocate Lt on device if not yet
1749: factors->iLt_d = MatRowMapKokkosView("factors->iLt_d", n + 1); // KK requires this view to be initialized to 0 to call transpose_matrix
1750: factors->jLt_d = MatColIdxKokkosView(NoInit("factors->jLt_d"), factors->jL_d.extent(0));
1751: factors->aLt_d = MatScalarKokkosView(NoInit("factors->aLt_d"), factors->aL_d.extent(0));
1752: }
1754: if (factors->iL_h.extent(0)) { // If L is on host, we also compute the transpose on host
1755: if (!factors->L) {
1756: Mat_SeqAIJ *seq;
1758: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, n, n, factors->iL_h.data(), factors->jL_h.data(), factors->aL_h.data(), &factors->L));
1759: PetscCall(MatTranspose(factors->L, MAT_INITIAL_MATRIX, &factors->Lt));
1761: seq = static_cast<Mat_SeqAIJ *>(factors->Lt->data);
1762: factors->iLt_h = MatRowMapKokkosViewHost(seq->i, n + 1);
1763: factors->jLt_h = MatColIdxKokkosViewHost(seq->j, seq->nz);
1764: factors->aLt_h = MatScalarKokkosViewHost(seq->a, seq->nz);
1765: } else {
1766: PetscCall(MatTranspose(factors->L, MAT_REUSE_MATRIX, &factors->Lt)); // Matrix Lt' data is aliased with {i, j, a}Lt_h
1767: }
1768: // Copy Lt from host to device
1769: PetscCallCXX(Kokkos::deep_copy(factors->iLt_d, factors->iLt_h));
1770: PetscCallCXX(Kokkos::deep_copy(factors->jLt_d, factors->jLt_h));
1771: PetscCallCXX(Kokkos::deep_copy(factors->aLt_d, factors->aLt_h));
1772: } else { // If L was computed on device, we also compute the transpose there
1773: // TODO: KK transpose_matrix() does not sort column indices, however cusparse requires sorted indices. We have to sort the indices, until KK provides finer control options.
1774: PetscCallCXX(transpose_matrix<ConstMatRowMapKokkosView, ConstMatColIdxKokkosView, ConstMatScalarKokkosView, MatRowMapKokkosView, MatColIdxKokkosView, MatScalarKokkosView, MatRowMapKokkosView, DefaultExecutionSpace>(n, n, factors->iL_d,
1775: factors->jL_d, factors->aL_d,
1776: factors->iLt_d, factors->jLt_d,
1777: factors->aLt_d));
1778: PetscCallCXX(sort_crs_matrix<DefaultExecutionSpace, MatRowMapKokkosView, MatColIdxKokkosView, MatScalarKokkosView>(factors->iLt_d, factors->jLt_d, factors->aLt_d));
1779: }
1780: PetscCallCXX(sptrsv_symbolic(&factors->khLt, factors->iLt_d, factors->jLt_d, factors->aLt_d));
1781: }
1783: factors->transpose_updated = PETSC_TRUE;
1784: }
1785: PetscFunctionReturn(PETSC_SUCCESS);
1786: }
1788: // Solve Ax = b, with RAR = U^T D U, where R is the row (and col) permutation matrix on A.
1789: // R is represented by rowperm in factors. If R is identity (i.e, no reordering), then rowperm is empty.
1790: static PetscErrorCode MatSolve_SeqAIJKokkos_Cholesky(Mat A, Vec bb, Vec xx)
1791: {
1792: auto exec = PetscGetKokkosExecutionSpace();
1793: Mat_SeqAIJKokkosTriFactors *factors = (Mat_SeqAIJKokkosTriFactors *)A->spptr;
1794: PetscInt m = A->rmap->n;
1795: PetscScalarKokkosView D = factors->D_d;
1796: PetscScalarKokkosView X, Y, B; // alias
1797: ConstPetscScalarKokkosView b;
1798: PetscScalarKokkosView x;
1799: PetscIntKokkosView &rowperm = factors->rowperm;
1800: PetscBool identity = rowperm.extent(0) ? PETSC_FALSE : PETSC_TRUE;
1802: PetscFunctionBegin;
1803: PetscCall(PetscLogGpuTimeBegin());
1804: PetscCall(MatSeqAIJKokkosSolveCheck(A)); // for UX = T
1805: PetscCall(MatSeqAIJKokkosTransposeSolveCheck(A)); // for U^T Y = B
1806: PetscCall(VecGetKokkosView(bb, &b));
1807: PetscCall(VecGetKokkosViewWrite(xx, &x));
1809: // Solve U^T Y = B
1810: if (identity) { // Reorder b with the row permutation
1811: B = PetscScalarKokkosView(const_cast<PetscScalar *>(b.data()), b.extent(0));
1812: Y = factors->workVector;
1813: } else {
1814: B = factors->workVector;
1815: PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(exec, 0, m), KOKKOS_LAMBDA(const PetscInt i) { B(i) = b(rowperm(i)); }));
1816: Y = x;
1817: }
1818: PetscCallCXX(sptrsv_solve(exec, &factors->khUt, factors->iUt_d, factors->jUt_d, factors->aUt_d, B, Y));
1820: // Solve diag(D) Y' = Y.
1821: // Actually just do Y' = Y*D since D is already inverted in MatCholeskyFactorNumeric_SeqAIJ(). It is basically a vector element-wise multiplication.
1822: PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(exec, 0, m), KOKKOS_LAMBDA(const PetscInt i) { Y(i) = Y(i) * D(i); }));
1824: // Solve UX = Y
1825: if (identity) {
1826: X = x;
1827: } else {
1828: X = factors->workVector; // B is not needed anymore
1829: }
1830: PetscCallCXX(sptrsv_solve(exec, &factors->khU, factors->iU_d, factors->jU_d, factors->aU_d, Y, X));
1832: // Reorder X with the inverse column (row) permutation
1833: if (!identity) PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(exec, 0, m), KOKKOS_LAMBDA(const PetscInt i) { x(rowperm(i)) = X(i); }));
1835: PetscCall(VecRestoreKokkosView(bb, &b));
1836: PetscCall(VecRestoreKokkosViewWrite(xx, &x));
1837: PetscCall(PetscLogGpuTimeEnd());
1838: PetscFunctionReturn(PETSC_SUCCESS);
1839: }
1841: // Solve Ax = b, with RAC = LU, where R and C are row and col permutation matrices on A respectively.
1842: // R and C are represented by rowperm and colperm in factors.
1843: // If R or C is identity (i.e, no reordering), then rowperm or colperm is empty.
1844: static PetscErrorCode MatSolve_SeqAIJKokkos_LU(Mat A, Vec bb, Vec xx)
1845: {
1846: auto exec = PetscGetKokkosExecutionSpace();
1847: Mat_SeqAIJKokkosTriFactors *factors = (Mat_SeqAIJKokkosTriFactors *)A->spptr;
1848: PetscInt m = A->rmap->n;
1849: PetscScalarKokkosView X, Y, B; // alias
1850: ConstPetscScalarKokkosView b;
1851: PetscScalarKokkosView x;
1852: PetscIntKokkosView &rowperm = factors->rowperm;
1853: PetscIntKokkosView &colperm = factors->colperm;
1854: PetscBool row_identity = rowperm.extent(0) ? PETSC_FALSE : PETSC_TRUE;
1855: PetscBool col_identity = colperm.extent(0) ? PETSC_FALSE : PETSC_TRUE;
1857: PetscFunctionBegin;
1858: PetscCall(PetscLogGpuTimeBegin());
1859: PetscCall(MatSeqAIJKokkosSolveCheck(A));
1860: PetscCall(VecGetKokkosView(bb, &b));
1861: PetscCall(VecGetKokkosViewWrite(xx, &x));
1863: // Solve L Y = B (i.e., L (U C^- x) = R b). R b indicates applying the row permutation on b.
1864: if (row_identity) {
1865: B = PetscScalarKokkosView(const_cast<PetscScalar *>(b.data()), b.extent(0));
1866: Y = factors->workVector;
1867: } else {
1868: B = factors->workVector;
1869: PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(exec, 0, m), KOKKOS_LAMBDA(const PetscInt i) { B(i) = b(rowperm(i)); }));
1870: Y = x;
1871: }
1872: PetscCallCXX(sptrsv_solve(exec, &factors->khL, factors->iL_d, factors->jL_d, factors->aL_d, B, Y));
1874: // Solve U C^- x = Y
1875: if (col_identity) {
1876: X = x;
1877: } else {
1878: X = factors->workVector;
1879: }
1880: PetscCallCXX(sptrsv_solve(exec, &factors->khU, factors->iU_d, factors->jU_d, factors->aU_d, Y, X));
1882: // x = C X; Reorder X with the inverse col permutation
1883: if (!col_identity) PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(exec, 0, m), KOKKOS_LAMBDA(const PetscInt i) { x(colperm(i)) = X(i); }));
1885: PetscCall(VecRestoreKokkosView(bb, &b));
1886: PetscCall(VecRestoreKokkosViewWrite(xx, &x));
1887: PetscCall(PetscLogGpuTimeEnd());
1888: PetscFunctionReturn(PETSC_SUCCESS);
1889: }
1891: // Solve A^T x = b, with RAC = LU, where R and C are row and col permutation matrices on A respectively.
1892: // R and C are represented by rowperm and colperm in factors.
1893: // If R or C is identity (i.e, no reordering), then rowperm or colperm is empty.
1894: // A = R^-1 L U C^-1, so A^T = C^-T U^T L^T R^-T. But since C^- = C^T, R^- = R^T, we have A^T = C U^T L^T R.
1895: static PetscErrorCode MatSolveTranspose_SeqAIJKokkos_LU(Mat A, Vec bb, Vec xx)
1896: {
1897: auto exec = PetscGetKokkosExecutionSpace();
1898: Mat_SeqAIJKokkosTriFactors *factors = (Mat_SeqAIJKokkosTriFactors *)A->spptr;
1899: PetscInt m = A->rmap->n;
1900: PetscScalarKokkosView X, Y, B; // alias
1901: ConstPetscScalarKokkosView b;
1902: PetscScalarKokkosView x;
1903: PetscIntKokkosView &rowperm = factors->rowperm;
1904: PetscIntKokkosView &colperm = factors->colperm;
1905: PetscBool row_identity = rowperm.extent(0) ? PETSC_FALSE : PETSC_TRUE;
1906: PetscBool col_identity = colperm.extent(0) ? PETSC_FALSE : PETSC_TRUE;
1908: PetscFunctionBegin;
1909: PetscCall(PetscLogGpuTimeBegin());
1910: PetscCall(MatSeqAIJKokkosTransposeSolveCheck(A)); // Update L^T, U^T if needed, and do sptrsv symbolic for L^T, U^T
1911: PetscCall(VecGetKokkosView(bb, &b));
1912: PetscCall(VecGetKokkosViewWrite(xx, &x));
1914: // Solve U^T Y = B (i.e., U^T (L^T R x) = C^- b). Note C^- b = C^T b, which means applying the column permutation on b.
1915: if (col_identity) { // Reorder b with the col permutation
1916: B = PetscScalarKokkosView(const_cast<PetscScalar *>(b.data()), b.extent(0));
1917: Y = factors->workVector;
1918: } else {
1919: B = factors->workVector;
1920: PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(exec, 0, m), KOKKOS_LAMBDA(const PetscInt i) { B(i) = b(colperm(i)); }));
1921: Y = x;
1922: }
1923: PetscCallCXX(sptrsv_solve(exec, &factors->khUt, factors->iUt_d, factors->jUt_d, factors->aUt_d, B, Y));
1925: // Solve L^T X = Y
1926: if (row_identity) {
1927: X = x;
1928: } else {
1929: X = factors->workVector;
1930: }
1931: PetscCallCXX(sptrsv_solve(exec, &factors->khLt, factors->iLt_d, factors->jLt_d, factors->aLt_d, Y, X));
1933: // x = R^- X = R^T X; Reorder X with the inverse row permutation
1934: if (!row_identity) PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(exec, 0, m), KOKKOS_LAMBDA(const PetscInt i) { x(rowperm(i)) = X(i); }));
1936: PetscCall(VecRestoreKokkosView(bb, &b));
1937: PetscCall(VecRestoreKokkosViewWrite(xx, &x));
1938: PetscCall(PetscLogGpuTimeEnd());
1939: PetscFunctionReturn(PETSC_SUCCESS);
1940: }
1942: static PetscErrorCode MatLUFactorNumeric_SeqAIJKokkos(Mat B, Mat A, const MatFactorInfo *info)
1943: {
1944: PetscFunctionBegin;
1945: PetscCall(MatSeqAIJKokkosSyncHost(A));
1946: PetscCall(MatLUFactorNumeric_SeqAIJ(B, A, info));
1948: if (!info->solveonhost) { // if solve on host, then we don't need to copy L, U to device
1949: Mat_SeqAIJKokkosTriFactors *factors = (Mat_SeqAIJKokkosTriFactors *)B->spptr;
1950: Mat_SeqAIJ *b = static_cast<Mat_SeqAIJ *>(B->data);
1951: const PetscInt *Bi = b->i, *Bj = b->j, *Bdiag = b->diag;
1952: const MatScalar *Ba = b->a;
1953: PetscInt m = B->rmap->n, n = B->cmap->n;
1955: if (factors->iL_h.extent(0) == 0) { // Allocate memory and copy the L, U structure for the first time
1956: // Allocate memory and copy the structure
1957: factors->iL_h = MatRowMapKokkosViewHost(NoInit("iL_h"), m + 1);
1958: factors->jL_h = MatColIdxKokkosViewHost(NoInit("jL_h"), (Bi[m] - Bi[0]) + m); // + the diagonal entries
1959: factors->aL_h = MatScalarKokkosViewHost(NoInit("aL_h"), (Bi[m] - Bi[0]) + m);
1960: factors->iU_h = MatRowMapKokkosViewHost(NoInit("iU_h"), m + 1);
1961: factors->jU_h = MatColIdxKokkosViewHost(NoInit("jU_h"), (Bdiag[0] - Bdiag[m]));
1962: factors->aU_h = MatScalarKokkosViewHost(NoInit("aU_h"), (Bdiag[0] - Bdiag[m]));
1964: PetscInt *Li = factors->iL_h.data();
1965: PetscInt *Lj = factors->jL_h.data();
1966: PetscInt *Ui = factors->iU_h.data();
1967: PetscInt *Uj = factors->jU_h.data();
1969: Li[0] = Ui[0] = 0;
1970: for (PetscInt i = 0; i < m; i++) {
1971: PetscInt llen = Bi[i + 1] - Bi[i]; // exclusive of the diagonal entry
1972: PetscInt ulen = Bdiag[i] - Bdiag[i + 1]; // inclusive of the diagonal entry
1974: PetscCall(PetscArraycpy(Lj + Li[i], Bj + Bi[i], llen)); // entries of L on the left of the diagonal
1975: Lj[Li[i] + llen] = i; // diagonal entry of L
1977: Uj[Ui[i]] = i; // diagonal entry of U
1978: PetscCall(PetscArraycpy(Uj + Ui[i] + 1, Bj + Bdiag[i + 1] + 1, ulen - 1)); // entries of U on the right of the diagonal
1980: Li[i + 1] = Li[i] + llen + 1;
1981: Ui[i + 1] = Ui[i] + ulen;
1982: }
1984: factors->iL_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), factors->iL_h);
1985: factors->jL_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), factors->jL_h);
1986: factors->iU_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), factors->iU_h);
1987: factors->jU_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), factors->jU_h);
1988: factors->aL_d = Kokkos::create_mirror_view(DefaultMemorySpace(), factors->aL_h);
1989: factors->aU_d = Kokkos::create_mirror_view(DefaultMemorySpace(), factors->aU_h);
1991: // Copy row/col permutation to device
1992: IS rowperm = ((Mat_SeqAIJ *)B->data)->row;
1993: PetscBool row_identity;
1994: PetscCall(ISIdentity(rowperm, &row_identity));
1995: if (!row_identity) {
1996: const PetscInt *ip;
1998: PetscCall(ISGetIndices(rowperm, &ip));
1999: factors->rowperm = PetscIntKokkosView(NoInit("rowperm"), m);
2000: PetscCallCXX(Kokkos::deep_copy(factors->rowperm, PetscIntKokkosViewHost(const_cast<PetscInt *>(ip), m)));
2001: PetscCall(ISRestoreIndices(rowperm, &ip));
2002: PetscCall(PetscLogCpuToGpu(m * sizeof(PetscInt)));
2003: }
2005: IS colperm = ((Mat_SeqAIJ *)B->data)->col;
2006: PetscBool col_identity;
2007: PetscCall(ISIdentity(colperm, &col_identity));
2008: if (!col_identity) {
2009: const PetscInt *ip;
2011: PetscCall(ISGetIndices(colperm, &ip));
2012: factors->colperm = PetscIntKokkosView(NoInit("colperm"), n);
2013: PetscCallCXX(Kokkos::deep_copy(factors->colperm, PetscIntKokkosViewHost(const_cast<PetscInt *>(ip), n)));
2014: PetscCall(ISRestoreIndices(colperm, &ip));
2015: PetscCall(PetscLogCpuToGpu(n * sizeof(PetscInt)));
2016: }
2018: /* Create sptrsv handles for L, U and their transpose */
2019: #if defined(KOKKOSKERNELS_ENABLE_TPL_CUSPARSE)
2020: auto sptrsv_alg = SPTRSVAlgorithm::SPTRSV_CUSPARSE;
2021: #else
2022: auto sptrsv_alg = SPTRSVAlgorithm::SEQLVLSCHD_TP1;
2023: #endif
2024: factors->khL.create_sptrsv_handle(sptrsv_alg, m, true /* L is lower tri */);
2025: factors->khU.create_sptrsv_handle(sptrsv_alg, m, false /* U is not lower tri */);
2026: factors->khLt.create_sptrsv_handle(sptrsv_alg, m, false /* L^T is not lower tri */);
2027: factors->khUt.create_sptrsv_handle(sptrsv_alg, m, true /* U^T is lower tri */);
2028: }
2030: // Copy the value
2031: for (PetscInt i = 0; i < m; i++) {
2032: PetscInt llen = Bi[i + 1] - Bi[i];
2033: PetscInt ulen = Bdiag[i] - Bdiag[i + 1];
2034: const PetscInt *Li = factors->iL_h.data();
2035: const PetscInt *Ui = factors->iU_h.data();
2037: PetscScalar *La = factors->aL_h.data();
2038: PetscScalar *Ua = factors->aU_h.data();
2040: PetscCall(PetscArraycpy(La + Li[i], Ba + Bi[i], llen)); // entries of L
2041: La[Li[i] + llen] = 1.0; // diagonal entry
2043: Ua[Ui[i]] = 1.0 / Ba[Bdiag[i]]; // diagonal entry
2044: PetscCall(PetscArraycpy(Ua + Ui[i] + 1, Ba + Bdiag[i + 1] + 1, ulen - 1)); // entries of U
2045: }
2047: PetscCallCXX(Kokkos::deep_copy(factors->aL_d, factors->aL_h));
2048: PetscCallCXX(Kokkos::deep_copy(factors->aU_d, factors->aU_h));
2049: // Once the factors' values have changed, we need to update their transpose and redo sptrsv symbolic
2050: factors->transpose_updated = PETSC_FALSE;
2051: factors->sptrsv_symbolic_completed = PETSC_FALSE;
2053: B->ops->solve = MatSolve_SeqAIJKokkos_LU;
2054: B->ops->solvetranspose = MatSolveTranspose_SeqAIJKokkos_LU;
2055: }
2057: B->ops->matsolve = NULL;
2058: B->ops->matsolvetranspose = NULL;
2059: PetscFunctionReturn(PETSC_SUCCESS);
2060: }
2062: static PetscErrorCode MatILUFactorNumeric_SeqAIJKokkos_ILU0(Mat B, Mat A, const MatFactorInfo *info)
2063: {
2064: Mat_SeqAIJKokkos *aijkok = (Mat_SeqAIJKokkos *)A->spptr;
2065: Mat_SeqAIJKokkosTriFactors *factors = (Mat_SeqAIJKokkosTriFactors *)B->spptr;
2066: PetscInt fill_lev = info->levels;
2068: PetscFunctionBegin;
2069: PetscCall(PetscLogGpuTimeBegin());
2070: PetscCheck(!info->factoronhost, PetscObjectComm((PetscObject)A), PETSC_ERR_PLIB, "MatFactorInfo.factoronhost should be false");
2071: PetscCall(MatSeqAIJKokkosSyncDevice(A));
2073: auto a_d = aijkok->a_dual.view_device();
2074: auto i_d = aijkok->i_dual.view_device();
2075: auto j_d = aijkok->j_dual.view_device();
2077: PetscCallCXX(spiluk_numeric(&factors->kh, fill_lev, i_d, j_d, a_d, factors->iL_d, factors->jL_d, factors->aL_d, factors->iU_d, factors->jU_d, factors->aU_d));
2079: B->assembled = PETSC_TRUE;
2080: B->preallocated = PETSC_TRUE;
2081: B->ops->solve = MatSolve_SeqAIJKokkos_LU;
2082: B->ops->solvetranspose = MatSolveTranspose_SeqAIJKokkos_LU;
2083: B->ops->matsolve = NULL;
2084: B->ops->matsolvetranspose = NULL;
2086: /* Once the factors' value changed, we need to update their transpose and sptrsv handle */
2087: factors->transpose_updated = PETSC_FALSE;
2088: factors->sptrsv_symbolic_completed = PETSC_FALSE;
2089: /* TODO: log flops, but how to know that? */
2090: PetscCall(PetscLogGpuTimeEnd());
2091: PetscFunctionReturn(PETSC_SUCCESS);
2092: }
2094: // Use KK's spiluk_symbolic() to do ILU0 symbolic factorization, with no row/col reordering
2095: static PetscErrorCode MatILUFactorSymbolic_SeqAIJKokkos_ILU0(Mat B, Mat A, IS, IS, const MatFactorInfo *info)
2096: {
2097: Mat_SeqAIJKokkos *aijkok;
2098: Mat_SeqAIJ *b;
2099: Mat_SeqAIJKokkosTriFactors *factors = (Mat_SeqAIJKokkosTriFactors *)B->spptr;
2100: PetscInt fill_lev = info->levels;
2101: PetscInt nnzA = ((Mat_SeqAIJ *)A->data)->nz, nnzL, nnzU;
2102: PetscInt n = A->rmap->n;
2104: PetscFunctionBegin;
2105: PetscCheck(!info->factoronhost, PetscObjectComm((PetscObject)A), PETSC_ERR_PLIB, "MatFactorInfo's factoronhost should be false as we are doing it on device right now");
2106: PetscCall(MatSeqAIJKokkosSyncDevice(A));
2108: /* Create a spiluk handle and then do symbolic factorization */
2109: nnzL = nnzU = PetscRealIntMultTruncate(info->fill, nnzA);
2110: factors->kh.create_spiluk_handle(SPILUKAlgorithm::SEQLVLSCHD_TP1, n, nnzL, nnzU);
2112: auto spiluk_handle = factors->kh.get_spiluk_handle();
2114: Kokkos::realloc(factors->iL_d, n + 1); /* Free old arrays and realloc */
2115: Kokkos::realloc(factors->jL_d, spiluk_handle->get_nnzL());
2116: Kokkos::realloc(factors->iU_d, n + 1);
2117: Kokkos::realloc(factors->jU_d, spiluk_handle->get_nnzU());
2119: aijkok = (Mat_SeqAIJKokkos *)A->spptr;
2120: auto i_d = aijkok->i_dual.view_device();
2121: auto j_d = aijkok->j_dual.view_device();
2122: PetscCallCXX(spiluk_symbolic(&factors->kh, fill_lev, i_d, j_d, factors->iL_d, factors->jL_d, factors->iU_d, factors->jU_d));
2123: /* TODO: if spiluk_symbolic is asynchronous, do we need to sync before calling get_nnzL()? */
2125: Kokkos::resize(factors->jL_d, spiluk_handle->get_nnzL()); /* Shrink or expand, and retain old value */
2126: Kokkos::resize(factors->jU_d, spiluk_handle->get_nnzU());
2127: Kokkos::realloc(factors->aL_d, spiluk_handle->get_nnzL()); /* No need to retain old value */
2128: Kokkos::realloc(factors->aU_d, spiluk_handle->get_nnzU());
2130: /* TODO: add options to select sptrsv algorithms */
2131: /* Create sptrsv handles for L, U and their transpose */
2132: #if defined(KOKKOSKERNELS_ENABLE_TPL_CUSPARSE)
2133: auto sptrsv_alg = SPTRSVAlgorithm::SPTRSV_CUSPARSE;
2134: #else
2135: auto sptrsv_alg = SPTRSVAlgorithm::SEQLVLSCHD_TP1;
2136: #endif
2138: factors->khL.create_sptrsv_handle(sptrsv_alg, n, true /* L is lower tri */);
2139: factors->khU.create_sptrsv_handle(sptrsv_alg, n, false /* U is not lower tri */);
2140: factors->khLt.create_sptrsv_handle(sptrsv_alg, n, false /* L^T is not lower tri */);
2141: factors->khUt.create_sptrsv_handle(sptrsv_alg, n, true /* U^T is lower tri */);
2143: /* Fill fields of the factor matrix B */
2144: PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(B, MAT_SKIP_ALLOCATION, NULL));
2145: b = (Mat_SeqAIJ *)B->data;
2146: b->nz = b->maxnz = spiluk_handle->get_nnzL() + spiluk_handle->get_nnzU();
2147: B->info.fill_ratio_given = info->fill;
2148: B->info.fill_ratio_needed = nnzA > 0 ? ((PetscReal)b->nz) / ((PetscReal)nnzA) : 1.0;
2150: B->ops->lufactornumeric = MatILUFactorNumeric_SeqAIJKokkos_ILU0;
2151: PetscFunctionReturn(PETSC_SUCCESS);
2152: }
2154: static PetscErrorCode MatLUFactorSymbolic_SeqAIJKokkos(Mat B, Mat A, IS isrow, IS iscol, const MatFactorInfo *info)
2155: {
2156: PetscFunctionBegin;
2157: PetscCall(MatLUFactorSymbolic_SeqAIJ(B, A, isrow, iscol, info));
2158: PetscCheck(!B->spptr, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Expected a NULL spptr");
2159: PetscCallCXX(B->spptr = new Mat_SeqAIJKokkosTriFactors(B->rmap->n));
2160: B->ops->lufactornumeric = MatLUFactorNumeric_SeqAIJKokkos;
2161: PetscFunctionReturn(PETSC_SUCCESS);
2162: }
2164: static PetscErrorCode MatILUFactorSymbolic_SeqAIJKokkos(Mat B, Mat A, IS isrow, IS iscol, const MatFactorInfo *info)
2165: {
2166: PetscBool row_identity = PETSC_FALSE, col_identity = PETSC_FALSE;
2168: PetscFunctionBegin;
2169: if (!info->factoronhost) {
2170: PetscCall(ISIdentity(isrow, &row_identity));
2171: PetscCall(ISIdentity(iscol, &col_identity));
2172: }
2174: PetscCheck(!B->spptr, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Expected a NULL spptr");
2175: PetscCallCXX(B->spptr = new Mat_SeqAIJKokkosTriFactors(B->rmap->n));
2177: if (!info->factoronhost && !info->levels && row_identity && col_identity) { // if level 0 and no reordering
2178: PetscCall(MatILUFactorSymbolic_SeqAIJKokkos_ILU0(B, A, isrow, iscol, info));
2179: } else {
2180: PetscCall(MatILUFactorSymbolic_SeqAIJ(B, A, isrow, iscol, info)); // otherwise, use PETSc's ILU on host
2181: B->ops->lufactornumeric = MatLUFactorNumeric_SeqAIJKokkos;
2182: }
2183: PetscFunctionReturn(PETSC_SUCCESS);
2184: }
2186: static PetscErrorCode MatCholeskyFactorNumeric_SeqAIJKokkos(Mat B, Mat A, const MatFactorInfo *info)
2187: {
2188: PetscFunctionBegin;
2189: PetscCall(MatSeqAIJKokkosSyncHost(A));
2190: PetscCall(MatCholeskyFactorNumeric_SeqAIJ(B, A, info));
2192: if (!info->solveonhost) { // if solve on host, then we don't need to copy L, U to device
2193: Mat_SeqAIJKokkosTriFactors *factors = (Mat_SeqAIJKokkosTriFactors *)B->spptr;
2194: Mat_SeqAIJ *b = static_cast<Mat_SeqAIJ *>(B->data);
2195: const PetscInt *Bi = b->i, *Bj = b->j, *Bdiag = b->diag;
2196: const MatScalar *Ba = b->a;
2197: PetscInt m = B->rmap->n;
2199: if (factors->iU_h.extent(0) == 0) { // First time of numeric factorization
2200: // Allocate memory and copy the structure
2201: factors->iU_h = PetscIntKokkosViewHost(const_cast<PetscInt *>(Bi), m + 1); // wrap Bi as iU_h
2202: factors->jU_h = MatColIdxKokkosViewHost(NoInit("jU_h"), Bi[m]);
2203: factors->aU_h = MatScalarKokkosViewHost(NoInit("aU_h"), Bi[m]);
2204: factors->D_h = MatScalarKokkosViewHost(NoInit("D_h"), m);
2205: factors->aU_d = Kokkos::create_mirror_view(DefaultMemorySpace(), factors->aU_h);
2206: factors->D_d = Kokkos::create_mirror_view(DefaultMemorySpace(), factors->D_h);
2208: // Build jU_h from the skewed Aj
2209: PetscInt *Uj = factors->jU_h.data();
2210: for (PetscInt i = 0; i < m; i++) {
2211: PetscInt ulen = Bi[i + 1] - Bi[i];
2212: Uj[Bi[i]] = i; // diagonal entry
2213: PetscCall(PetscArraycpy(Uj + Bi[i] + 1, Bj + Bi[i], ulen - 1)); // entries of U on the right of the diagonal
2214: }
2216: // Copy iU, jU to device
2217: PetscCallCXX(factors->iU_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), factors->iU_h));
2218: PetscCallCXX(factors->jU_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), factors->jU_h));
2220: // Copy row/col permutation to device
2221: IS rowperm = ((Mat_SeqAIJ *)B->data)->row;
2222: PetscBool row_identity;
2223: PetscCall(ISIdentity(rowperm, &row_identity));
2224: if (!row_identity) {
2225: const PetscInt *ip;
2227: PetscCall(ISGetIndices(rowperm, &ip));
2228: PetscCallCXX(factors->rowperm = PetscIntKokkosView(NoInit("rowperm"), m));
2229: PetscCallCXX(Kokkos::deep_copy(factors->rowperm, PetscIntKokkosViewHost(const_cast<PetscInt *>(ip), m)));
2230: PetscCall(ISRestoreIndices(rowperm, &ip));
2231: PetscCall(PetscLogCpuToGpu(m * sizeof(PetscInt)));
2232: }
2234: // Create sptrsv handles for U and U^T
2235: #if defined(KOKKOSKERNELS_ENABLE_TPL_CUSPARSE)
2236: auto sptrsv_alg = SPTRSVAlgorithm::SPTRSV_CUSPARSE;
2237: #else
2238: auto sptrsv_alg = SPTRSVAlgorithm::SEQLVLSCHD_TP1;
2239: #endif
2240: factors->khU.create_sptrsv_handle(sptrsv_alg, m, false /* U is not lower tri */);
2241: factors->khUt.create_sptrsv_handle(sptrsv_alg, m, true /* U^T is lower tri */);
2242: }
2243: // These pointers were set MatCholeskyFactorNumeric_SeqAIJ(), so we always need to update them
2244: B->ops->solve = MatSolve_SeqAIJKokkos_Cholesky;
2245: B->ops->solvetranspose = MatSolve_SeqAIJKokkos_Cholesky;
2247: // Copy the value
2248: PetscScalar *Ua = factors->aU_h.data();
2249: PetscScalar *D = factors->D_h.data();
2250: for (PetscInt i = 0; i < m; i++) {
2251: D[i] = Ba[Bdiag[i]]; // actually Aa[Adiag[i]] is the inverse of the diagonal
2252: Ua[Bi[i]] = (PetscScalar)1.0; // set the unit diagonal for U
2253: for (PetscInt k = 0; k < Bi[i + 1] - Bi[i] - 1; k++) Ua[Bi[i] + 1 + k] = -Ba[Bi[i] + k];
2254: }
2255: PetscCallCXX(Kokkos::deep_copy(factors->aU_d, factors->aU_h));
2256: PetscCallCXX(Kokkos::deep_copy(factors->D_d, factors->D_h));
2258: factors->sptrsv_symbolic_completed = PETSC_FALSE; // When numeric value changed, we must do these again
2259: factors->transpose_updated = PETSC_FALSE;
2260: }
2262: B->ops->matsolve = NULL;
2263: B->ops->matsolvetranspose = NULL;
2264: PetscFunctionReturn(PETSC_SUCCESS);
2265: }
2267: static PetscErrorCode MatICCFactorSymbolic_SeqAIJKokkos(Mat B, Mat A, IS perm, const MatFactorInfo *info)
2268: {
2269: PetscFunctionBegin;
2270: if (info->solveonhost) {
2271: // If solve on host, we have to change the type, as eventually we need to call MatSolve_SeqSBAIJ_1_NaturalOrdering() etc.
2272: PetscCall(MatSetType(B, MATSEQSBAIJ));
2273: PetscCall(MatSeqSBAIJSetPreallocation(B, 1, MAT_SKIP_ALLOCATION, NULL));
2274: }
2276: PetscCall(MatICCFactorSymbolic_SeqAIJ(B, A, perm, info));
2278: if (!info->solveonhost) {
2279: // If solve on device, B is still a MATSEQAIJKOKKOS, so we are good to allocate B->spptr
2280: PetscCheck(!B->spptr, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Expected a NULL spptr");
2281: PetscCallCXX(B->spptr = new Mat_SeqAIJKokkosTriFactors(B->rmap->n));
2282: B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqAIJKokkos;
2283: }
2284: PetscFunctionReturn(PETSC_SUCCESS);
2285: }
2287: static PetscErrorCode MatCholeskyFactorSymbolic_SeqAIJKokkos(Mat B, Mat A, IS perm, const MatFactorInfo *info)
2288: {
2289: PetscFunctionBegin;
2290: if (info->solveonhost) {
2291: // If solve on host, we have to change the type, as eventually we need to call MatSolve_SeqSBAIJ_1_NaturalOrdering() etc.
2292: PetscCall(MatSetType(B, MATSEQSBAIJ));
2293: PetscCall(MatSeqSBAIJSetPreallocation(B, 1, MAT_SKIP_ALLOCATION, NULL));
2294: }
2296: PetscCall(MatCholeskyFactorSymbolic_SeqAIJ(B, A, perm, info)); // it sets B's two ISes ((Mat_SeqAIJ*)B->data)->{row, col} to perm
2298: if (!info->solveonhost) {
2299: // If solve on device, B is still a MATSEQAIJKOKKOS, so we are good to allocate B->spptr
2300: PetscCheck(!B->spptr, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Expected a NULL spptr");
2301: PetscCallCXX(B->spptr = new Mat_SeqAIJKokkosTriFactors(B->rmap->n));
2302: B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqAIJKokkos;
2303: }
2304: PetscFunctionReturn(PETSC_SUCCESS);
2305: }
2307: // The _Kokkos suffix means we will use Kokkos as a solver for the SeqAIJKokkos matrix
2308: static PetscErrorCode MatFactorGetSolverType_SeqAIJKokkos_Kokkos(Mat A, MatSolverType *type)
2309: {
2310: PetscFunctionBegin;
2311: *type = MATSOLVERKOKKOS;
2312: PetscFunctionReturn(PETSC_SUCCESS);
2313: }
2315: /*MC
2316: MATSOLVERKOKKOS = "Kokkos" - A matrix solver type providing triangular solvers for sequential matrices
2317: on a single GPU of type, `MATSEQAIJKOKKOS`, `MATAIJKOKKOS`.
2319: Level: beginner
2321: .seealso: [](ch_matrices), `Mat`, `PCFactorSetMatSolverType()`, `MatSolverType`, `MatCreateSeqAIJKokkos()`, `MATAIJKOKKOS`
2322: M*/
2323: PETSC_EXTERN PetscErrorCode MatGetFactor_SeqAIJKokkos_Kokkos(Mat A, MatFactorType ftype, Mat *B) /* MatGetFactor_<MatType>_<MatSolverType> */
2324: {
2325: PetscInt n = A->rmap->n;
2326: MPI_Comm comm;
2328: PetscFunctionBegin;
2329: PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
2330: PetscCall(MatCreate(comm, B));
2331: PetscCall(MatSetSizes(*B, n, n, n, n));
2332: PetscCall(MatSetBlockSizesFromMats(*B, A, A));
2333: (*B)->factortype = ftype;
2334: PetscCall(MatSetType(*B, MATSEQAIJKOKKOS));
2335: PetscCall(MatSeqAIJSetPreallocation(*B, MAT_SKIP_ALLOCATION, NULL));
2336: PetscCheck(!(*B)->spptr, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Expected a NULL spptr");
2338: if (ftype == MAT_FACTOR_LU || ftype == MAT_FACTOR_ILU || ftype == MAT_FACTOR_ILUDT) {
2339: (*B)->ops->lufactorsymbolic = MatLUFactorSymbolic_SeqAIJKokkos;
2340: (*B)->ops->ilufactorsymbolic = MatILUFactorSymbolic_SeqAIJKokkos;
2341: PetscCall(PetscStrallocpy(MATORDERINGND, (char **)&(*B)->preferredordering[MAT_FACTOR_LU]));
2342: PetscCall(PetscStrallocpy(MATORDERINGNATURAL, (char **)&(*B)->preferredordering[MAT_FACTOR_ILU]));
2343: PetscCall(PetscStrallocpy(MATORDERINGNATURAL, (char **)&(*B)->preferredordering[MAT_FACTOR_ILUDT]));
2344: } else if (ftype == MAT_FACTOR_CHOLESKY || ftype == MAT_FACTOR_ICC) {
2345: (*B)->ops->iccfactorsymbolic = MatICCFactorSymbolic_SeqAIJKokkos;
2346: (*B)->ops->choleskyfactorsymbolic = MatCholeskyFactorSymbolic_SeqAIJKokkos;
2347: PetscCall(PetscStrallocpy(MATORDERINGND, (char **)&(*B)->preferredordering[MAT_FACTOR_CHOLESKY]));
2348: PetscCall(PetscStrallocpy(MATORDERINGNATURAL, (char **)&(*B)->preferredordering[MAT_FACTOR_ICC]));
2349: } else SETERRQ(comm, PETSC_ERR_SUP, "MatFactorType %s is not supported by MatType SeqAIJKokkos", MatFactorTypes[ftype]);
2351: // The factorization can use the ordering provided in MatLUFactorSymbolic(), MatCholeskyFactorSymbolic() etc, though we do it on host
2352: (*B)->canuseordering = PETSC_TRUE;
2353: PetscCall(PetscObjectComposeFunction((PetscObject)*B, "MatFactorGetSolverType_C", MatFactorGetSolverType_SeqAIJKokkos_Kokkos));
2354: PetscFunctionReturn(PETSC_SUCCESS);
2355: }
2357: PETSC_INTERN PetscErrorCode MatSolverTypeRegister_Kokkos(void)
2358: {
2359: PetscFunctionBegin;
2360: PetscCall(MatSolverTypeRegister(MATSOLVERKOKKOS, MATSEQAIJKOKKOS, MAT_FACTOR_LU, MatGetFactor_SeqAIJKokkos_Kokkos));
2361: PetscCall(MatSolverTypeRegister(MATSOLVERKOKKOS, MATSEQAIJKOKKOS, MAT_FACTOR_CHOLESKY, MatGetFactor_SeqAIJKokkos_Kokkos));
2362: PetscCall(MatSolverTypeRegister(MATSOLVERKOKKOS, MATSEQAIJKOKKOS, MAT_FACTOR_ILU, MatGetFactor_SeqAIJKokkos_Kokkos));
2363: PetscCall(MatSolverTypeRegister(MATSOLVERKOKKOS, MATSEQAIJKOKKOS, MAT_FACTOR_ICC, MatGetFactor_SeqAIJKokkos_Kokkos));
2364: PetscFunctionReturn(PETSC_SUCCESS);
2365: }
2367: /* Utility to print out a KokkosCsrMatrix for debugging */
2368: PETSC_INTERN PetscErrorCode PrintCsrMatrix(const KokkosCsrMatrix &csrmat)
2369: {
2370: const auto &iv = Kokkos::create_mirror_view_and_copy(HostMirrorMemorySpace(), csrmat.graph.row_map);
2371: const auto &jv = Kokkos::create_mirror_view_and_copy(HostMirrorMemorySpace(), csrmat.graph.entries);
2372: const auto &av = Kokkos::create_mirror_view_and_copy(HostMirrorMemorySpace(), csrmat.values);
2373: const PetscInt *i = iv.data();
2374: const PetscInt *j = jv.data();
2375: const PetscScalar *a = av.data();
2376: PetscInt m = csrmat.numRows(), n = csrmat.numCols(), nnz = csrmat.nnz();
2378: PetscFunctionBegin;
2379: PetscCall(PetscPrintf(PETSC_COMM_SELF, "%" PetscInt_FMT " x %" PetscInt_FMT " SeqAIJKokkos, with %" PetscInt_FMT " nonzeros\n", m, n, nnz));
2380: for (PetscInt k = 0; k < m; k++) {
2381: PetscCall(PetscPrintf(PETSC_COMM_SELF, "%" PetscInt_FMT ": ", k));
2382: for (PetscInt p = i[k]; p < i[k + 1]; p++) PetscCall(PetscPrintf(PETSC_COMM_SELF, "%" PetscInt_FMT "(%.1f), ", j[p], (double)PetscRealPart(a[p])));
2383: PetscCall(PetscPrintf(PETSC_COMM_SELF, "\n"));
2384: }
2385: PetscFunctionReturn(PETSC_SUCCESS);
2386: }