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>
9: #include <KokkosBlas.hpp>
10: #include <KokkosSparse_CrsMatrix.hpp>
12: // To suppress compiler warnings:
13: // /path/include/KokkosSparse_spmv_bsrmatrix_tpl_spec_decl.hpp:434:63:
14: // warning: 'cusparseStatus_t cusparseDbsrmm(cusparseHandle_t, cusparseDirection_t, cusparseOperation_t,
15: // cusparseOperation_t, int, int, int, int, const double*, cusparseMatDescr_t, const double*, const int*, const int*,
16: // int, const double*, int, const double*, double*, int)' is deprecated: please use cusparseSpMM instead [-Wdeprecated-declarations]
17: #define DISABLE_CUSPARSE_DEPRECATED
18: #include <KokkosSparse_spmv.hpp>
20: #include <KokkosSparse_spiluk.hpp>
21: #include <KokkosSparse_sptrsv.hpp>
22: #include <KokkosSparse_spgemm.hpp>
23: #include <KokkosSparse_spadd.hpp>
24: #include <KokkosBatched_LU_Decl.hpp>
25: #include <KokkosBatched_InverseLU_Decl.hpp>
27: #include <../src/mat/impls/aij/seq/kokkos/aijkok.hpp>
29: #if PETSC_PKG_KOKKOS_KERNELS_VERSION_GE(3, 7, 0)
30: #include <KokkosSparse_Utils.hpp>
31: using KokkosSparse::sort_crs_matrix;
32: using KokkosSparse::Impl::transpose_matrix;
33: #else
34: #include <KokkosKernels_Sorting.hpp>
35: using KokkosKernels::sort_crs_matrix;
36: using KokkosKernels::Impl::transpose_matrix;
37: #endif
39: #if PETSC_PKG_KOKKOS_KERNELS_VERSION_GE(4, 6, 0)
40: using KokkosSparse::spiluk_symbolic;
41: using KokkosSparse::spiluk_numeric;
42: using KokkosSparse::sptrsv_symbolic;
43: using KokkosSparse::sptrsv_solve;
44: using KokkosSparse::Experimental::SPTRSVAlgorithm;
45: using KokkosSparse::Experimental::SPILUKAlgorithm;
46: #else
47: using KokkosSparse::Experimental::spiluk_symbolic;
48: using KokkosSparse::Experimental::spiluk_numeric;
49: using KokkosSparse::Experimental::sptrsv_symbolic;
50: using KokkosSparse::Experimental::sptrsv_solve;
51: using KokkosSparse::Experimental::SPTRSVAlgorithm;
52: using KokkosSparse::Experimental::SPILUKAlgorithm;
53: #endif
55: static PetscErrorCode MatSetOps_SeqAIJKokkos(Mat); /* Forward declaration */
57: /* MatAssemblyEnd_SeqAIJKokkos() happens when we finalized nonzeros of the matrix, either after
58: we assembled the matrix on host, or after we directly produced the matrix data on device (ex., through MatMatMult).
59: In the latter case, it is important to set a_dual's sync state correctly.
60: */
61: static PetscErrorCode MatAssemblyEnd_SeqAIJKokkos(Mat A, MatAssemblyType mode)
62: {
63: Mat_SeqAIJ *aijseq;
64: Mat_SeqAIJKokkos *aijkok;
66: PetscFunctionBegin;
67: if (mode == MAT_FLUSH_ASSEMBLY) PetscFunctionReturn(PETSC_SUCCESS);
68: PetscCall(MatAssemblyEnd_SeqAIJ(A, mode));
70: aijseq = static_cast<Mat_SeqAIJ *>(A->data);
71: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
73: /* If aijkok does not exist, we just copy i, j to device.
74: 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.
75: In both cases, we build a new aijkok structure.
76: */
77: if (!aijkok || aijkok->nonzerostate != A->nonzerostate) { /* aijkok might not exist yet or nonzero pattern has changed */
78: if (aijkok && aijkok->host_aij_allocated_by_kokkos) { /* Avoid accidentally freeing much needed a,i,j on host when deleting aijkok */
79: PetscCall(PetscShmgetAllocateArray(aijkok->nrows() + 1, sizeof(PetscInt), (void **)&aijseq->i));
80: PetscCall(PetscShmgetAllocateArray(aijkok->nnz(), sizeof(PetscInt), (void **)&aijseq->j));
81: PetscCall(PetscShmgetAllocateArray(aijkok->nnz(), sizeof(PetscInt), (void **)&aijseq->a));
82: PetscCall(PetscArraycpy(aijseq->i, aijkok->i_host_data(), aijkok->nrows() + 1));
83: PetscCall(PetscArraycpy(aijseq->j, aijkok->j_host_data(), aijkok->nnz()));
84: PetscCall(PetscArraycpy(aijseq->a, aijkok->a_host_data(), aijkok->nnz()));
85: aijseq->free_a = PETSC_TRUE;
86: aijseq->free_ij = PETSC_TRUE;
87: /* This arises from MatCreateSeqAIJKokkosWithKokkosCsrMatrix() used in MatMatMult, where
88: we have the CsrMatrix on device first and then copy to host, followed by
89: MatSetMPIAIJWithSplitSeqAIJ() with garray = NULL.
90: One could improve it by not using NULL garray.
91: */
92: }
93: delete aijkok;
94: aijkok = new Mat_SeqAIJKokkos(A, A->rmap->n, A->cmap->n, aijseq, A->nonzerostate, PETSC_FALSE /* don't copy mat values to device */);
95: A->spptr = aijkok;
96: } else if (A->rmap->n && aijkok->diag_dual.extent(0) == 0) { // MatProduct might directly produce AIJ on device, but not the diag.
97: PetscCall(aijkok->SetDiagonalMarkers(A));
98: }
99: PetscFunctionReturn(PETSC_SUCCESS);
100: }
102: /* Sync CSR data to device if not yet */
103: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatSeqAIJKokkosSyncDevice(Mat A)
104: {
105: Mat_SeqAIJKokkos *aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
107: PetscFunctionBegin;
108: PetscCheck(A->factortype == MAT_FACTOR_NONE, PetscObjectComm((PetscObject)A), PETSC_ERR_PLIB, "Can't sync factorized matrix from host to device");
109: PetscCheck(aijkok, PETSC_COMM_WORLD, PETSC_ERR_PLIB, "Unexpected NULL (Mat_SeqAIJKokkos*)A->spptr");
110: if (aijkok->a_dual.need_sync_device()) {
111: PetscCall(KokkosDualViewSyncDevice(aijkok->a_dual, PetscGetKokkosExecutionSpace()));
112: aijkok->transpose_updated = PETSC_FALSE; /* values of the transpose is out-of-date */
113: aijkok->hermitian_updated = PETSC_FALSE;
114: }
115: PetscFunctionReturn(PETSC_SUCCESS);
116: }
118: /* Mark the CSR data on device as modified */
119: PETSC_INTERN PetscErrorCode MatSeqAIJKokkosModifyDevice(Mat A)
120: {
121: Mat_SeqAIJKokkos *aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
123: PetscFunctionBegin;
124: PetscCheck(A->factortype == MAT_FACTOR_NONE, PetscObjectComm((PetscObject)A), PETSC_ERR_PLIB, "Not supported for factorized matries");
125: aijkok->a_dual.clear_sync_state();
126: aijkok->a_dual.modify_device();
127: aijkok->transpose_updated = PETSC_FALSE;
128: aijkok->hermitian_updated = PETSC_FALSE;
129: PetscCall(PetscObjectStateIncrease((PetscObject)A));
130: PetscFunctionReturn(PETSC_SUCCESS);
131: }
133: static PetscErrorCode MatSeqAIJKokkosSyncHost(Mat A)
134: {
135: Mat_SeqAIJKokkos *aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
136: auto exec = PetscGetKokkosExecutionSpace();
138: PetscFunctionBegin;
139: PetscCheckTypeName(A, MATSEQAIJKOKKOS);
140: /* We do not expect one needs factors on host */
141: PetscCheck(A->factortype == MAT_FACTOR_NONE, PetscObjectComm((PetscObject)A), PETSC_ERR_PLIB, "Can't sync factorized matrix from device to host");
142: PetscCheck(aijkok, PetscObjectComm((PetscObject)A), PETSC_ERR_PLIB, "Missing AIJKOK");
143: PetscCall(KokkosDualViewSyncHost(aijkok->a_dual, exec));
144: PetscFunctionReturn(PETSC_SUCCESS);
145: }
147: static PetscErrorCode MatSeqAIJGetArray_SeqAIJKokkos(Mat A, PetscScalar *array[])
148: {
149: Mat_SeqAIJKokkos *aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
151: PetscFunctionBegin;
152: /* aijkok contains valid pointers only if the host's nonzerostate matches with the device's.
153: Calling MatSeqAIJSetPreallocation() or MatSetValues() on host, where aijseq->{i,j,a} might be
154: reallocated, will lead to stale {i,j,a}_dual in aijkok. In both operations, the hosts's nonzerostate
155: must have been updated. The stale aijkok will be rebuilt during MatAssemblyEnd.
156: */
157: if (aijkok && A->nonzerostate == aijkok->nonzerostate) {
158: PetscCall(KokkosDualViewSyncHost(aijkok->a_dual, PetscGetKokkosExecutionSpace()));
159: *array = aijkok->a_dual.view_host().data();
160: } else { /* Happens when calling MatSetValues on a newly created matrix */
161: *array = static_cast<Mat_SeqAIJ *>(A->data)->a;
162: }
163: PetscFunctionReturn(PETSC_SUCCESS);
164: }
166: static PetscErrorCode MatSeqAIJRestoreArray_SeqAIJKokkos(Mat A, PetscScalar *array[])
167: {
168: Mat_SeqAIJKokkos *aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
170: PetscFunctionBegin;
171: if (aijkok && A->nonzerostate == aijkok->nonzerostate) aijkok->a_dual.modify_host();
172: PetscFunctionReturn(PETSC_SUCCESS);
173: }
175: static PetscErrorCode MatSeqAIJGetArrayRead_SeqAIJKokkos(Mat A, const PetscScalar *array[])
176: {
177: Mat_SeqAIJKokkos *aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
179: PetscFunctionBegin;
180: if (aijkok && A->nonzerostate == aijkok->nonzerostate) {
181: PetscCall(KokkosDualViewSyncHost(aijkok->a_dual, PetscGetKokkosExecutionSpace()));
182: *array = aijkok->a_dual.view_host().data();
183: } else {
184: *array = static_cast<Mat_SeqAIJ *>(A->data)->a;
185: }
186: PetscFunctionReturn(PETSC_SUCCESS);
187: }
189: static PetscErrorCode MatSeqAIJRestoreArrayRead_SeqAIJKokkos(Mat A, const PetscScalar *array[])
190: {
191: PetscFunctionBegin;
192: *array = NULL;
193: PetscFunctionReturn(PETSC_SUCCESS);
194: }
196: static PetscErrorCode MatSeqAIJGetArrayWrite_SeqAIJKokkos(Mat A, PetscScalar *array[])
197: {
198: Mat_SeqAIJKokkos *aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
200: PetscFunctionBegin;
201: if (aijkok && A->nonzerostate == aijkok->nonzerostate) {
202: *array = aijkok->a_dual.view_host().data();
203: } else { /* Ex. happens with MatZeroEntries on a preallocated but not assembled matrix */
204: *array = static_cast<Mat_SeqAIJ *>(A->data)->a;
205: }
206: PetscFunctionReturn(PETSC_SUCCESS);
207: }
209: static PetscErrorCode MatSeqAIJRestoreArrayWrite_SeqAIJKokkos(Mat A, PetscScalar *array[])
210: {
211: Mat_SeqAIJKokkos *aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
213: PetscFunctionBegin;
214: if (aijkok && A->nonzerostate == aijkok->nonzerostate) {
215: aijkok->a_dual.clear_sync_state();
216: aijkok->a_dual.modify_host();
217: }
218: PetscFunctionReturn(PETSC_SUCCESS);
219: }
221: static PetscErrorCode MatSeqAIJGetCSRAndMemType_SeqAIJKokkos(Mat A, const PetscInt **i, const PetscInt **j, PetscScalar **a, PetscMemType *mtype)
222: {
223: Mat_SeqAIJKokkos *aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
225: PetscFunctionBegin;
226: PetscCheck(aijkok != NULL, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "aijkok is NULL");
228: if (i) *i = aijkok->i_device_data();
229: if (j) *j = aijkok->j_device_data();
230: if (a) {
231: PetscCall(KokkosDualViewSyncDevice(aijkok->a_dual, PetscGetKokkosExecutionSpace()));
232: *a = aijkok->a_device_data();
233: }
234: if (mtype) *mtype = PETSC_MEMTYPE_KOKKOS;
235: PetscFunctionReturn(PETSC_SUCCESS);
236: }
238: static PetscErrorCode MatGetCurrentMemType_SeqAIJKokkos(PETSC_UNUSED Mat A, PetscMemType *mtype)
239: {
240: PetscFunctionBegin;
241: *mtype = PETSC_MEMTYPE_KOKKOS;
242: PetscFunctionReturn(PETSC_SUCCESS);
243: }
245: /*
246: Generate the sparsity pattern of a MatSeqAIJKokkos matrix's transpose on device.
248: Input Parameter:
249: . A - the MATSEQAIJKOKKOS matrix
251: Output Parameters:
252: + perm_d - the permutation array on device, which connects Ta(i) = Aa(perm(i))
253: - T_d - the transpose on device, whose value array is allocated but not initialized
254: */
255: static PetscErrorCode MatSeqAIJKokkosGenerateTransposeStructure(Mat A, MatRowMapKokkosView &perm_d, KokkosCsrMatrix &T_d)
256: {
257: Mat_SeqAIJ *aseq = static_cast<Mat_SeqAIJ *>(A->data);
258: PetscInt nz = aseq->nz, m = A->rmap->N, n = A->cmap->n;
259: const PetscInt *Ai = aseq->i, *Aj = aseq->j;
260: MatRowMapKokkosViewHost Ti_h(NoInit("Ti"), n + 1);
261: MatRowMapType *Ti = Ti_h.data();
262: MatColIdxKokkosViewHost Tj_h(NoInit("Tj"), nz);
263: MatRowMapKokkosViewHost perm_h(NoInit("permutation"), nz);
264: PetscInt *Tj = Tj_h.data();
265: PetscInt *perm = perm_h.data();
266: PetscInt *offset;
268: PetscFunctionBegin;
269: // Populate Ti
270: PetscCallCXX(Kokkos::deep_copy(Ti_h, 0));
271: Ti++;
272: for (PetscInt i = 0; i < nz; i++) Ti[Aj[i]]++;
273: Ti--;
274: for (PetscInt i = 0; i < n; i++) Ti[i + 1] += Ti[i];
276: // Populate Tj and the permutation array
277: PetscCall(PetscCalloc1(n, &offset)); // offset in each T row to fill in its column indices
278: for (PetscInt i = 0; i < m; i++) {
279: for (PetscInt j = Ai[i]; j < Ai[i + 1]; j++) { // A's (i,j) is T's (j,i)
280: PetscInt r = Aj[j]; // row r of T
281: PetscInt disp = Ti[r] + offset[r];
283: Tj[disp] = i; // col i of T
284: perm[disp] = j;
285: offset[r]++;
286: }
287: }
288: PetscCall(PetscFree(offset));
290: // Sort each row of T, along with the permutation array
291: for (PetscInt i = 0; i < n; i++) PetscCall(PetscSortIntWithArray(Ti[i + 1] - Ti[i], Tj + Ti[i], perm + Ti[i]));
293: // Output perm and T on device
294: auto Ti_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), Ti_h);
295: auto Tj_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), Tj_h);
296: PetscCallCXX(T_d = KokkosCsrMatrix("csrmatT", n, m, nz, MatScalarKokkosView("Ta", nz), Ti_d, Tj_d));
297: PetscCallCXX(perm_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), perm_h));
298: PetscFunctionReturn(PETSC_SUCCESS);
299: }
301: // Generate the transpose on device and cache it internally
302: // Note: KK transpose_matrix() does not have support symbolic/numeric transpose, so we do it on our own
303: PETSC_INTERN PetscErrorCode MatSeqAIJKokkosGenerateTranspose_Private(Mat A, KokkosCsrMatrix *csrmatT)
304: {
305: Mat_SeqAIJ *aseq = static_cast<Mat_SeqAIJ *>(A->data);
306: Mat_SeqAIJKokkos *akok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
307: PetscInt nz = aseq->nz, m = A->rmap->N, n = A->cmap->n;
308: KokkosCsrMatrix &T = akok->csrmatT;
310: PetscFunctionBegin;
311: PetscCheck(akok, PETSC_COMM_WORLD, PETSC_ERR_PLIB, "Unexpected NULL (Mat_SeqAIJKokkos*)A->spptr");
312: PetscCall(KokkosDualViewSyncDevice(akok->a_dual, PetscGetKokkosExecutionSpace())); // Sync A's values since we are going to access them on device
314: const auto &Aa = akok->a_dual.view_device();
316: if (A->symmetric == PETSC_BOOL3_TRUE) {
317: *csrmatT = akok->csrmat;
318: } else {
319: // See if we already have a cached transpose and its value is up to date
320: if (T.numRows() == n && T.numCols() == m) { // this indicates csrmatT had been generated before, otherwise T has 0 rows/cols after construction
321: if (!akok->transpose_updated) { // if the value is out of date, update the cached version
322: const auto &perm = akok->transpose_perm; // get the permutation array
323: auto &Ta = T.values;
325: PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, nz), KOKKOS_LAMBDA(const PetscInt i) { Ta(i) = Aa(perm(i)); }));
326: }
327: } else { // Generate T of size n x m for the first time
328: MatRowMapKokkosView perm;
330: PetscCall(MatSeqAIJKokkosGenerateTransposeStructure(A, perm, T));
331: akok->transpose_perm = perm; // cache the perm in this matrix for reuse
332: PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, nz), KOKKOS_LAMBDA(const PetscInt i) { T.values(i) = Aa(perm(i)); }));
333: }
334: akok->transpose_updated = PETSC_TRUE;
335: *csrmatT = akok->csrmatT;
336: }
337: PetscFunctionReturn(PETSC_SUCCESS);
338: }
340: // Generate the Hermitian on device and cache it internally
341: static PetscErrorCode MatSeqAIJKokkosGenerateHermitian_Private(Mat A, KokkosCsrMatrix *csrmatH)
342: {
343: Mat_SeqAIJ *aseq = static_cast<Mat_SeqAIJ *>(A->data);
344: Mat_SeqAIJKokkos *akok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
345: PetscInt nz = aseq->nz, m = A->rmap->N, n = A->cmap->n;
346: KokkosCsrMatrix &T = akok->csrmatH;
348: PetscFunctionBegin;
349: PetscCheck(akok, PETSC_COMM_WORLD, PETSC_ERR_PLIB, "Unexpected NULL (Mat_SeqAIJKokkos*)A->spptr");
350: PetscCall(KokkosDualViewSyncDevice(akok->a_dual, PetscGetKokkosExecutionSpace())); // Sync A's values since we are going to access them on device
352: const auto &Aa = akok->a_dual.view_device();
354: if (A->hermitian == PETSC_BOOL3_TRUE) {
355: *csrmatH = akok->csrmat;
356: } else {
357: // See if we already have a cached Hermitian and its value is up to date
358: if (T.numRows() == n && T.numCols() == m) { // this indicates csrmatT had been generated before, otherwise T has 0 rows/cols after construction
359: if (!akok->hermitian_updated) { // if the value is out of date, update the cached version
360: const auto &perm = akok->transpose_perm; // get the permutation array
361: auto &Ta = T.values;
363: PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, nz), KOKKOS_LAMBDA(const PetscInt i) { Ta(i) = PetscConj(Aa(perm(i))); }));
364: }
365: } else { // Generate T of size n x m for the first time
366: MatRowMapKokkosView perm;
368: PetscCall(MatSeqAIJKokkosGenerateTransposeStructure(A, perm, T));
369: akok->transpose_perm = perm; // cache the perm in this matrix for reuse
370: PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, nz), KOKKOS_LAMBDA(const PetscInt i) { T.values(i) = PetscConj(Aa(perm(i))); }));
371: }
372: akok->hermitian_updated = PETSC_TRUE;
373: *csrmatH = akok->csrmatH;
374: }
375: PetscFunctionReturn(PETSC_SUCCESS);
376: }
378: /* y = A x */
379: static PetscErrorCode MatMult_SeqAIJKokkos(Mat A, Vec xx, Vec yy)
380: {
381: Mat_SeqAIJKokkos *aijkok;
382: ConstPetscScalarKokkosView xv;
383: PetscScalarKokkosView yv;
385: PetscFunctionBegin;
386: PetscCall(PetscLogGpuTimeBegin());
387: PetscCall(MatSeqAIJKokkosSyncDevice(A));
388: PetscCall(VecGetKokkosView(xx, &xv));
389: PetscCall(VecGetKokkosViewWrite(yy, &yv));
390: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
391: PetscCallCXX(KokkosSparse::spmv(PetscGetKokkosExecutionSpace(), "N", 1.0 /*alpha*/, aijkok->csrmat, xv, 0.0 /*beta*/, yv)); /* y = alpha A x + beta y */
392: PetscCall(VecRestoreKokkosView(xx, &xv));
393: PetscCall(VecRestoreKokkosViewWrite(yy, &yv));
394: /* 2.0*nnz - numRows seems more accurate here but assumes there are no zero-rows. So a little sloppy here. */
395: PetscCall(PetscLogGpuFlops(2.0 * aijkok->csrmat.nnz()));
396: PetscCall(PetscLogGpuTimeEnd());
397: PetscFunctionReturn(PETSC_SUCCESS);
398: }
400: /* y = A^T x */
401: static PetscErrorCode MatMultTranspose_SeqAIJKokkos(Mat A, Vec xx, Vec yy)
402: {
403: Mat_SeqAIJKokkos *aijkok;
404: const char *mode;
405: ConstPetscScalarKokkosView xv;
406: PetscScalarKokkosView yv;
407: KokkosCsrMatrix csrmat;
409: PetscFunctionBegin;
410: PetscCall(PetscLogGpuTimeBegin());
411: PetscCall(MatSeqAIJKokkosSyncDevice(A));
412: PetscCall(VecGetKokkosView(xx, &xv));
413: PetscCall(VecGetKokkosViewWrite(yy, &yv));
414: if (A->form_explicit_transpose) {
415: PetscCall(MatSeqAIJKokkosGenerateTranspose_Private(A, &csrmat));
416: mode = "N";
417: } else {
418: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
419: csrmat = aijkok->csrmat;
420: mode = "T";
421: }
422: PetscCallCXX(KokkosSparse::spmv(PetscGetKokkosExecutionSpace(), mode, 1.0 /*alpha*/, csrmat, xv, 0.0 /*beta*/, yv)); /* y = alpha A^T x + beta y */
423: PetscCall(VecRestoreKokkosView(xx, &xv));
424: PetscCall(VecRestoreKokkosViewWrite(yy, &yv));
425: PetscCall(PetscLogGpuFlops(2.0 * csrmat.nnz()));
426: PetscCall(PetscLogGpuTimeEnd());
427: PetscFunctionReturn(PETSC_SUCCESS);
428: }
430: /* y = A^H x */
431: static PetscErrorCode MatMultHermitianTranspose_SeqAIJKokkos(Mat A, Vec xx, Vec yy)
432: {
433: Mat_SeqAIJKokkos *aijkok;
434: const char *mode;
435: ConstPetscScalarKokkosView xv;
436: PetscScalarKokkosView yv;
437: KokkosCsrMatrix csrmat;
439: PetscFunctionBegin;
440: PetscCall(PetscLogGpuTimeBegin());
441: PetscCall(MatSeqAIJKokkosSyncDevice(A));
442: PetscCall(VecGetKokkosView(xx, &xv));
443: PetscCall(VecGetKokkosViewWrite(yy, &yv));
444: if (A->form_explicit_transpose) {
445: PetscCall(MatSeqAIJKokkosGenerateHermitian_Private(A, &csrmat));
446: mode = "N";
447: } else {
448: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
449: csrmat = aijkok->csrmat;
450: mode = "C";
451: }
452: PetscCallCXX(KokkosSparse::spmv(PetscGetKokkosExecutionSpace(), mode, 1.0 /*alpha*/, csrmat, xv, 0.0 /*beta*/, yv)); /* y = alpha A^H x + beta y */
453: PetscCall(VecRestoreKokkosView(xx, &xv));
454: PetscCall(VecRestoreKokkosViewWrite(yy, &yv));
455: PetscCall(PetscLogGpuFlops(2.0 * csrmat.nnz()));
456: PetscCall(PetscLogGpuTimeEnd());
457: PetscFunctionReturn(PETSC_SUCCESS);
458: }
460: /* z = A x + y */
461: static PetscErrorCode MatMultAdd_SeqAIJKokkos(Mat A, Vec xx, Vec yy, Vec zz)
462: {
463: Mat_SeqAIJKokkos *aijkok;
464: ConstPetscScalarKokkosView xv;
465: PetscScalarKokkosView zv;
467: PetscFunctionBegin;
468: PetscCall(PetscLogGpuTimeBegin());
469: PetscCall(MatSeqAIJKokkosSyncDevice(A));
470: if (zz != yy) PetscCall(VecCopy(yy, zz)); // depending on yy's sync flags, zz might get its latest data on host
471: PetscCall(VecGetKokkosView(xx, &xv));
472: PetscCall(VecGetKokkosView(zz, &zv)); // do after VecCopy(yy, zz) to get the latest data on device
473: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
474: PetscCallCXX(KokkosSparse::spmv(PetscGetKokkosExecutionSpace(), "N", 1.0 /*alpha*/, aijkok->csrmat, xv, 1.0 /*beta*/, zv)); /* z = alpha A x + beta z */
475: PetscCall(VecRestoreKokkosView(xx, &xv));
476: PetscCall(VecRestoreKokkosView(zz, &zv));
477: PetscCall(PetscLogGpuFlops(2.0 * aijkok->csrmat.nnz()));
478: PetscCall(PetscLogGpuTimeEnd());
479: PetscFunctionReturn(PETSC_SUCCESS);
480: }
482: /* z = A^T x + y */
483: static PetscErrorCode MatMultTransposeAdd_SeqAIJKokkos(Mat A, Vec xx, Vec yy, Vec zz)
484: {
485: Mat_SeqAIJKokkos *aijkok;
486: const char *mode;
487: ConstPetscScalarKokkosView xv;
488: PetscScalarKokkosView zv;
489: KokkosCsrMatrix csrmat;
491: PetscFunctionBegin;
492: PetscCall(PetscLogGpuTimeBegin());
493: PetscCall(MatSeqAIJKokkosSyncDevice(A));
494: if (zz != yy) PetscCall(VecCopy(yy, zz));
495: PetscCall(VecGetKokkosView(xx, &xv));
496: PetscCall(VecGetKokkosView(zz, &zv));
497: if (A->form_explicit_transpose) {
498: PetscCall(MatSeqAIJKokkosGenerateTranspose_Private(A, &csrmat));
499: mode = "N";
500: } else {
501: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
502: csrmat = aijkok->csrmat;
503: mode = "T";
504: }
505: PetscCallCXX(KokkosSparse::spmv(PetscGetKokkosExecutionSpace(), mode, 1.0 /*alpha*/, csrmat, xv, 1.0 /*beta*/, zv)); /* z = alpha A^T x + beta z */
506: PetscCall(VecRestoreKokkosView(xx, &xv));
507: PetscCall(VecRestoreKokkosView(zz, &zv));
508: PetscCall(PetscLogGpuFlops(2.0 * csrmat.nnz()));
509: PetscCall(PetscLogGpuTimeEnd());
510: PetscFunctionReturn(PETSC_SUCCESS);
511: }
513: /* z = A^H x + y */
514: static PetscErrorCode MatMultHermitianTransposeAdd_SeqAIJKokkos(Mat A, Vec xx, Vec yy, Vec zz)
515: {
516: Mat_SeqAIJKokkos *aijkok;
517: const char *mode;
518: ConstPetscScalarKokkosView xv;
519: PetscScalarKokkosView zv;
520: KokkosCsrMatrix csrmat;
522: PetscFunctionBegin;
523: PetscCall(PetscLogGpuTimeBegin());
524: PetscCall(MatSeqAIJKokkosSyncDevice(A));
525: if (zz != yy) PetscCall(VecCopy(yy, zz));
526: PetscCall(VecGetKokkosView(xx, &xv));
527: PetscCall(VecGetKokkosView(zz, &zv));
528: if (A->form_explicit_transpose) {
529: PetscCall(MatSeqAIJKokkosGenerateHermitian_Private(A, &csrmat));
530: mode = "N";
531: } else {
532: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
533: csrmat = aijkok->csrmat;
534: mode = "C";
535: }
536: PetscCallCXX(KokkosSparse::spmv(PetscGetKokkosExecutionSpace(), mode, 1.0 /*alpha*/, csrmat, xv, 1.0 /*beta*/, zv)); /* z = alpha A^H x + beta z */
537: PetscCall(VecRestoreKokkosView(xx, &xv));
538: PetscCall(VecRestoreKokkosView(zz, &zv));
539: PetscCall(PetscLogGpuFlops(2.0 * csrmat.nnz()));
540: PetscCall(PetscLogGpuTimeEnd());
541: PetscFunctionReturn(PETSC_SUCCESS);
542: }
544: static PetscErrorCode MatSetOption_SeqAIJKokkos(Mat A, MatOption op, PetscBool flg)
545: {
546: Mat_SeqAIJKokkos *aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
548: PetscFunctionBegin;
549: switch (op) {
550: case MAT_FORM_EXPLICIT_TRANSPOSE:
551: /* need to destroy the transpose matrix if present to prevent from logic errors if flg is set to true later */
552: if (A->form_explicit_transpose && !flg && aijkok) PetscCall(aijkok->DestroyMatTranspose());
553: A->form_explicit_transpose = flg;
554: break;
555: default:
556: PetscCall(MatSetOption_SeqAIJ(A, op, flg));
557: break;
558: }
559: PetscFunctionReturn(PETSC_SUCCESS);
560: }
562: /* Depending on reuse, either build a new mat, or use the existing mat */
563: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJKokkos(Mat A, MatType mtype, MatReuse reuse, Mat *newmat)
564: {
565: Mat_SeqAIJ *aseq;
567: PetscFunctionBegin;
568: PetscCall(PetscKokkosInitializeCheck());
569: if (reuse == MAT_INITIAL_MATRIX) { /* Build a brand new mat */
570: PetscCall(MatDuplicate(A, MAT_COPY_VALUES, newmat));
571: PetscCall(MatSetType(*newmat, mtype));
572: } else if (reuse == MAT_REUSE_MATRIX) { /* Reuse the mat created before */
573: PetscCall(MatCopy(A, *newmat, SAME_NONZERO_PATTERN)); /* newmat is already a SeqAIJKokkos */
574: } else if (reuse == MAT_INPLACE_MATRIX) { /* newmat is A */
575: PetscCheck(A == *newmat, PetscObjectComm((PetscObject)A), PETSC_ERR_PLIB, "A != *newmat with MAT_INPLACE_MATRIX");
576: PetscCall(PetscFree(A->defaultvectype));
577: PetscCall(PetscStrallocpy(VECKOKKOS, &A->defaultvectype)); /* Allocate and copy the string */
578: PetscCall(PetscObjectChangeTypeName((PetscObject)A, MATSEQAIJKOKKOS));
579: PetscCall(MatSetOps_SeqAIJKokkos(A));
580: aseq = static_cast<Mat_SeqAIJ *>(A->data);
581: if (A->assembled) { /* Copy i, j (but not values) to device for an assembled matrix if not yet */
582: PetscCheck(!A->spptr, PETSC_COMM_WORLD, PETSC_ERR_PLIB, "Expect NULL (Mat_SeqAIJKokkos*)A->spptr");
583: A->spptr = new Mat_SeqAIJKokkos(A, A->rmap->n, A->cmap->n, aseq, A->nonzerostate, PETSC_FALSE);
584: }
585: }
586: PetscFunctionReturn(PETSC_SUCCESS);
587: }
589: /* MatDuplicate always creates a new matrix. MatDuplicate can be called either on an assembled matrix or
590: an unassembled matrix, even though MAT_COPY_VALUES is not allowed for unassembled matrix.
591: */
592: static PetscErrorCode MatDuplicate_SeqAIJKokkos(Mat A, MatDuplicateOption dupOption, Mat *B)
593: {
594: Mat_SeqAIJ *bseq;
595: Mat_SeqAIJKokkos *akok = static_cast<Mat_SeqAIJKokkos *>(A->spptr), *bkok;
596: Mat mat;
598: PetscFunctionBegin;
599: /* Do not copy values on host as A's latest values might be on device. We don't want to do sync blindly */
600: PetscCall(MatDuplicate_SeqAIJ(A, MAT_DO_NOT_COPY_VALUES, B));
601: mat = *B;
602: if (A->assembled) {
603: bseq = static_cast<Mat_SeqAIJ *>(mat->data);
604: bkok = new Mat_SeqAIJKokkos(mat, mat->rmap->n, mat->cmap->n, bseq, mat->nonzerostate, PETSC_FALSE);
605: bkok->a_dual.clear_sync_state(); /* Clear B's sync state as it will be decided below */
606: /* Now copy values to B if needed */
607: if (dupOption == MAT_COPY_VALUES) {
608: if (akok->a_dual.need_sync_device()) {
609: Kokkos::deep_copy(bkok->a_dual.view_host(), akok->a_dual.view_host());
610: bkok->a_dual.modify_host();
611: } else { /* If device has the latest data, we only copy data on device */
612: Kokkos::deep_copy(bkok->a_dual.view_device(), akok->a_dual.view_device());
613: bkok->a_dual.modify_device();
614: }
615: } else { /* MAT_DO_NOT_COPY_VALUES or MAT_SHARE_NONZERO_PATTERN. B's values should be zeroed */
616: /* B's values on host should be already zeroed by MatDuplicate_SeqAIJ() */
617: bkok->a_dual.modify_host();
618: }
619: mat->spptr = bkok;
620: }
622: PetscCall(PetscFree(mat->defaultvectype));
623: PetscCall(PetscStrallocpy(VECKOKKOS, &mat->defaultvectype)); /* Allocate and copy the string */
624: PetscCall(PetscObjectChangeTypeName((PetscObject)mat, MATSEQAIJKOKKOS));
625: PetscCall(MatSetOps_SeqAIJKokkos(mat));
626: PetscFunctionReturn(PETSC_SUCCESS);
627: }
629: static PetscErrorCode MatTranspose_SeqAIJKokkos(Mat A, MatReuse reuse, Mat *B)
630: {
631: Mat At;
632: KokkosCsrMatrix internT;
633: Mat_SeqAIJKokkos *atkok, *bkok;
635: PetscFunctionBegin;
636: if (reuse == MAT_REUSE_MATRIX) PetscCall(MatTransposeCheckNonzeroState_Private(A, *B));
637: PetscCall(MatSeqAIJKokkosGenerateTranspose_Private(A, &internT)); /* Generate a transpose internally */
638: if (reuse == MAT_INITIAL_MATRIX || reuse == MAT_INPLACE_MATRIX) {
639: /* Deep copy internT, as we want to isolate the internal transpose */
640: PetscCallCXX(atkok = new Mat_SeqAIJKokkos(KokkosCsrMatrix("csrmat", internT)));
641: PetscCall(MatCreateSeqAIJKokkosWithCSRMatrix(PetscObjectComm((PetscObject)A), atkok, &At));
642: if (reuse == MAT_INITIAL_MATRIX) *B = At;
643: else PetscCall(MatHeaderReplace(A, &At)); /* Replace A with At inplace */
644: } else { /* MAT_REUSE_MATRIX, just need to copy values to B on device */
645: if ((*B)->assembled) {
646: bkok = static_cast<Mat_SeqAIJKokkos *>((*B)->spptr);
647: PetscCallCXX(Kokkos::deep_copy(bkok->a_dual.view_device(), internT.values));
648: PetscCall(MatSeqAIJKokkosModifyDevice(*B));
649: } else if ((*B)->preallocated) { /* It is ok for B to be only preallocated, as needed in MatTranspose_MPIAIJ */
650: Mat_SeqAIJ *bseq = static_cast<Mat_SeqAIJ *>((*B)->data);
651: MatScalarKokkosViewHost a_h(bseq->a, internT.nnz()); /* bseq->nz = 0 if unassembled */
652: MatColIdxKokkosViewHost j_h(bseq->j, internT.nnz());
653: PetscCallCXX(Kokkos::deep_copy(a_h, internT.values));
654: PetscCallCXX(Kokkos::deep_copy(j_h, internT.graph.entries));
655: } else SETERRQ(PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "B must be assembled or preallocated");
656: }
657: PetscFunctionReturn(PETSC_SUCCESS);
658: }
660: static PetscErrorCode MatDestroy_SeqAIJKokkos(Mat A)
661: {
662: Mat_SeqAIJKokkos *aijkok;
664: PetscFunctionBegin;
665: if (A->factortype == MAT_FACTOR_NONE) {
666: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
667: delete aijkok;
668: } else {
669: delete static_cast<Mat_SeqAIJKokkosTriFactors *>(A->spptr);
670: }
671: A->spptr = NULL;
672: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatFactorGetSolverType_C", NULL));
673: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSetPreallocationCOO_C", NULL));
674: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSetValuesCOO_C", NULL));
675: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijkokkos_seqdense_C", NULL));
676: #if PetscDefined(HAVE_CUDA)
677: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijkokkos_seqdensecuda_C", NULL));
678: #endif
679: #if PetscDefined(HAVE_HIP)
680: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijkokkos_seqdensehip_C", NULL));
681: #endif
682: #if PetscDefined(HAVE_HYPRE)
683: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaijkokkos_hypre_C", NULL));
684: #endif
685: PetscCall(MatDestroy_SeqAIJ(A));
686: PetscFunctionReturn(PETSC_SUCCESS);
687: }
689: /*MC
690: MATSEQAIJKOKKOS - MATAIJKOKKOS = "(seq)aijkokkos" - A matrix type to be used for sparse matrices with Kokkos
692: A matrix type using Kokkos-Kernels CrsMatrix type for portability across different device types
694: Options Database Key:
695: . -mat_type aijkokkos - sets the matrix type to `MATSEQAIJKOKKOS` during a call to `MatSetFromOptions()`
697: Level: beginner
699: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqAIJKokkos()`, `MATMPIAIJKOKKOS`
700: M*/
701: PETSC_EXTERN PetscErrorCode MatCreate_SeqAIJKokkos(Mat A)
702: {
703: PetscFunctionBegin;
704: PetscCall(PetscKokkosInitializeCheck());
705: PetscCall(MatCreate_SeqAIJ(A));
706: PetscCall(MatConvert_SeqAIJ_SeqAIJKokkos(A, MATSEQAIJKOKKOS, MAT_INPLACE_MATRIX, &A));
707: PetscFunctionReturn(PETSC_SUCCESS);
708: }
710: /* 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) */
711: PetscErrorCode MatSeqAIJKokkosMergeMats(Mat A, Mat B, MatReuse reuse, Mat *C)
712: {
713: Mat_SeqAIJ *a, *b;
714: Mat_SeqAIJKokkos *akok, *bkok, *ckok;
715: MatScalarKokkosView aa, ba, ca;
716: MatRowMapKokkosView ai, bi, ci;
717: MatColIdxKokkosView aj, bj, cj;
718: PetscInt m, n, nnz, aN;
720: PetscFunctionBegin;
723: PetscAssertPointer(C, 4);
724: PetscCheckTypeName(A, MATSEQAIJKOKKOS);
725: PetscCheckTypeName(B, MATSEQAIJKOKKOS);
726: 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);
727: PetscCheck(reuse != MAT_INPLACE_MATRIX, PETSC_COMM_SELF, PETSC_ERR_SUP, "MAT_INPLACE_MATRIX not supported");
729: PetscCall(MatSeqAIJKokkosSyncDevice(A));
730: PetscCall(MatSeqAIJKokkosSyncDevice(B));
731: a = static_cast<Mat_SeqAIJ *>(A->data);
732: b = static_cast<Mat_SeqAIJ *>(B->data);
733: akok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
734: bkok = static_cast<Mat_SeqAIJKokkos *>(B->spptr);
735: aa = akok->a_dual.view_device();
736: ai = akok->i_dual.view_device();
737: ba = bkok->a_dual.view_device();
738: bi = bkok->i_dual.view_device();
739: m = A->rmap->n; /* M, N and nnz of C */
740: n = A->cmap->n + B->cmap->n;
741: nnz = a->nz + b->nz;
742: aN = A->cmap->n; /* N of A */
743: if (reuse == MAT_INITIAL_MATRIX) {
744: aj = akok->j_dual.view_device();
745: bj = bkok->j_dual.view_device();
746: auto ca = MatScalarKokkosView("a", aa.extent(0) + ba.extent(0));
747: auto ci = MatRowMapKokkosView("i", ai.extent(0));
748: auto cj = MatColIdxKokkosView("j", aj.extent(0) + bj.extent(0));
750: /* Concatenate A and B in parallel using Kokkos hierarchical parallelism */
751: Kokkos::parallel_for(
752: Kokkos::TeamPolicy<>(PetscGetKokkosExecutionSpace(), m, Kokkos::AUTO()), KOKKOS_LAMBDA(const KokkosTeamMemberType &t) {
753: PetscInt i = t.league_rank(); /* row i */
754: PetscInt coffset = ai(i) + bi(i), alen = ai(i + 1) - ai(i), blen = bi(i + 1) - bi(i);
756: Kokkos::single(Kokkos::PerTeam(t), [=]() { /* this side effect only happens once per whole team */
757: ci(i) = coffset;
758: if (i == m - 1) ci(m) = ai(m) + bi(m);
759: });
761: Kokkos::parallel_for(Kokkos::TeamThreadRange(t, alen + blen), [&](PetscInt k) {
762: if (k < alen) {
763: ca(coffset + k) = aa(ai(i) + k);
764: cj(coffset + k) = aj(ai(i) + k);
765: } else {
766: ca(coffset + k) = ba(bi(i) + k - alen);
767: cj(coffset + k) = bj(bi(i) + k - alen) + aN; /* Entries in B get new column indices in C */
768: }
769: });
770: });
771: PetscCallCXX(ckok = new Mat_SeqAIJKokkos(m, n, nnz, ci, cj, ca));
772: PetscCall(MatCreateSeqAIJKokkosWithCSRMatrix(PETSC_COMM_SELF, ckok, C));
773: } else if (reuse == MAT_REUSE_MATRIX) {
775: PetscCheckTypeName(*C, MATSEQAIJKOKKOS);
776: ckok = static_cast<Mat_SeqAIJKokkos *>((*C)->spptr);
777: ca = ckok->a_dual.view_device();
778: ci = ckok->i_dual.view_device();
780: Kokkos::parallel_for(
781: Kokkos::TeamPolicy<>(PetscGetKokkosExecutionSpace(), m, Kokkos::AUTO()), KOKKOS_LAMBDA(const KokkosTeamMemberType &t) {
782: PetscInt i = t.league_rank(); /* row i */
783: PetscInt alen = ai(i + 1) - ai(i), blen = bi(i + 1) - bi(i);
784: Kokkos::parallel_for(Kokkos::TeamThreadRange(t, alen + blen), [&](PetscInt k) {
785: if (k < alen) ca(ci(i) + k) = aa(ai(i) + k);
786: else ca(ci(i) + k) = ba(bi(i) + k - alen);
787: });
788: });
789: PetscCall(MatSeqAIJKokkosModifyDevice(*C));
790: }
791: PetscFunctionReturn(PETSC_SUCCESS);
792: }
794: static PetscErrorCode MatProductCtxDestroy_SeqAIJKokkos(PetscCtxRt pdata)
795: {
796: PetscFunctionBegin;
797: delete *reinterpret_cast<MatProductCtx_SeqAIJKokkos **>(pdata);
798: PetscFunctionReturn(PETSC_SUCCESS);
799: }
801: static PetscErrorCode MatProductNumeric_SeqAIJKokkos_SeqAIJKokkos(Mat C)
802: {
803: Mat_Product *product = C->product;
804: Mat A, B;
805: bool transA, transB; /* use bool, since KK needs this type */
806: Mat_SeqAIJKokkos *akok, *bkok, *ckok;
807: Mat_SeqAIJ *c;
808: MatProductCtx_SeqAIJKokkos *pdata;
809: KokkosCsrMatrix csrmatA, csrmatB;
811: PetscFunctionBegin;
812: MatCheckProduct(C, 1);
813: PetscCheck(C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data empty");
814: pdata = static_cast<MatProductCtx_SeqAIJKokkos *>(C->product->data);
816: // See if numeric has already been done in symbolic (e.g., user calls MatMatMult(A,B,MAT_INITIAL_MATRIX,..,C)).
817: // If yes, skip the numeric, but reset the flag so that next time when user calls MatMatMult(E,F,MAT_REUSE_MATRIX,..,C),
818: // we still do numeric.
819: if (pdata->reusesym) { // numeric reuses results from symbolic
820: pdata->reusesym = PETSC_FALSE;
821: PetscFunctionReturn(PETSC_SUCCESS);
822: }
824: switch (product->type) {
825: case MATPRODUCT_AB:
826: transA = false;
827: transB = false;
828: break;
829: case MATPRODUCT_AtB:
830: transA = true;
831: transB = false;
832: break;
833: case MATPRODUCT_ABt:
834: transA = false;
835: transB = true;
836: break;
837: default:
838: SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Unsupported product type %s", MatProductTypes[product->type]);
839: }
841: A = product->A;
842: B = product->B;
843: PetscCall(MatSeqAIJKokkosSyncDevice(A));
844: PetscCall(MatSeqAIJKokkosSyncDevice(B));
845: akok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
846: bkok = static_cast<Mat_SeqAIJKokkos *>(B->spptr);
847: ckok = static_cast<Mat_SeqAIJKokkos *>(C->spptr);
849: PetscCheck(ckok, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Device data structure spptr is empty");
851: csrmatA = akok->csrmat;
852: csrmatB = bkok->csrmat;
854: /* TODO: Once KK spgemm implements transpose, we can get rid of the explicit transpose here */
855: if (transA) {
856: PetscCall(MatSeqAIJKokkosGenerateTranspose_Private(A, &csrmatA));
857: transA = false;
858: }
860: if (transB) {
861: PetscCall(MatSeqAIJKokkosGenerateTranspose_Private(B, &csrmatB));
862: transB = false;
863: }
864: PetscCall(PetscLogGpuTimeBegin());
865: PetscCallCXX(KokkosSparse::spgemm_numeric(pdata->kh, csrmatA, transA, csrmatB, transB, ckok->csrmat));
866: #if PETSC_PKG_KOKKOS_KERNELS_VERSION_LT(4, 0, 0)
867: auto spgemmHandle = pdata->kh.get_spgemm_handle();
868: if (spgemmHandle->get_sort_option() != 1) PetscCallCXX(sort_crs_matrix(ckok->csrmat)); /* without sort, mat_tests-ex62_14_seqaijkokkos fails */
869: #endif
871: PetscCall(PetscLogGpuTimeEnd());
872: PetscCall(MatSeqAIJKokkosModifyDevice(C));
873: /* shorter version of MatAssemblyEnd_SeqAIJ */
874: c = (Mat_SeqAIJ *)C->data;
875: 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));
876: PetscCall(PetscInfo(C, "Number of mallocs during MatSetValues() is 0\n"));
877: PetscCall(PetscInfo(C, "Maximum nonzeros in any row is %" PetscInt_FMT "\n", c->rmax));
878: c->reallocs = 0;
879: C->info.mallocs = 0;
880: C->info.nz_unneeded = 0;
881: C->assembled = C->was_assembled = PETSC_TRUE;
882: C->num_ass++;
883: PetscFunctionReturn(PETSC_SUCCESS);
884: }
886: static PetscErrorCode MatProductSymbolic_SeqAIJKokkos_SeqAIJKokkos(Mat C)
887: {
888: Mat_Product *product = C->product;
889: MatProductType ptype;
890: Mat A, B;
891: bool transA, transB;
892: Mat_SeqAIJKokkos *akok, *bkok, *ckok;
893: MatProductCtx_SeqAIJKokkos *pdata;
894: MPI_Comm comm;
895: KokkosCsrMatrix csrmatA, csrmatB, csrmatC;
897: PetscFunctionBegin;
898: MatCheckProduct(C, 1);
899: PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
900: PetscCheck(!product->data, comm, PETSC_ERR_PLIB, "Product data not empty");
901: A = product->A;
902: B = product->B;
903: PetscCall(MatSeqAIJKokkosSyncDevice(A));
904: PetscCall(MatSeqAIJKokkosSyncDevice(B));
905: akok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
906: bkok = static_cast<Mat_SeqAIJKokkos *>(B->spptr);
907: csrmatA = akok->csrmat;
908: csrmatB = bkok->csrmat;
910: ptype = product->type;
911: // Take advantage of the symmetry if true
912: if (A->symmetric == PETSC_BOOL3_TRUE && ptype == MATPRODUCT_AtB) {
913: ptype = MATPRODUCT_AB;
914: product->symbolic_used_the_fact_A_is_symmetric = PETSC_TRUE;
915: }
916: if (B->symmetric == PETSC_BOOL3_TRUE && ptype == MATPRODUCT_ABt) {
917: ptype = MATPRODUCT_AB;
918: product->symbolic_used_the_fact_B_is_symmetric = PETSC_TRUE;
919: }
921: switch (ptype) {
922: case MATPRODUCT_AB:
923: transA = false;
924: transB = false;
925: PetscCall(MatSetBlockSizesFromMats(C, A, B));
926: break;
927: case MATPRODUCT_AtB:
928: transA = true;
929: transB = false;
930: if (A->cmap->bs > 0) PetscCall(PetscLayoutSetBlockSize(C->rmap, A->cmap->bs));
931: if (B->cmap->bs > 0) PetscCall(PetscLayoutSetBlockSize(C->cmap, B->cmap->bs));
932: break;
933: case MATPRODUCT_ABt:
934: transA = false;
935: transB = true;
936: if (A->rmap->bs > 0) PetscCall(PetscLayoutSetBlockSize(C->rmap, A->rmap->bs));
937: if (B->rmap->bs > 0) PetscCall(PetscLayoutSetBlockSize(C->cmap, B->rmap->bs));
938: break;
939: default:
940: SETERRQ(comm, PETSC_ERR_PLIB, "Unsupported product type %s", MatProductTypes[product->type]);
941: }
942: PetscCallCXX(product->data = pdata = new MatProductCtx_SeqAIJKokkos());
943: pdata->reusesym = product->api_user;
945: /* TODO: add command line options to select spgemm algorithms */
946: auto spgemm_alg = KokkosSparse::SPGEMMAlgorithm::SPGEMM_DEFAULT; /* default alg is TPL if enabled, otherwise KK */
948: PetscCallCXX(pdata->kh.create_spgemm_handle(spgemm_alg));
950: PetscCall(PetscLogGpuTimeBegin());
951: /* TODO: Get rid of the explicit transpose once KK-spgemm implements the transpose option */
952: if (transA) {
953: PetscCall(MatSeqAIJKokkosGenerateTranspose_Private(A, &csrmatA));
954: transA = false;
955: }
957: if (transB) {
958: PetscCall(MatSeqAIJKokkosGenerateTranspose_Private(B, &csrmatB));
959: transB = false;
960: }
962: PetscCallCXX(KokkosSparse::spgemm_symbolic(pdata->kh, csrmatA, transA, csrmatB, transB, csrmatC));
963: /* spgemm_symbolic() only populates C's rowmap, but not C's column indices.
964: So we have to do a fake spgemm_numeric() here to get csrmatC.j_d setup, before
965: calling new Mat_SeqAIJKokkos().
966: TODO: Remove the fake spgemm_numeric() after KK fixed this problem.
967: */
968: PetscCallCXX(KokkosSparse::spgemm_numeric(pdata->kh, csrmatA, transA, csrmatB, transB, csrmatC));
969: #if PETSC_PKG_KOKKOS_KERNELS_VERSION_LT(4, 0, 0)
970: /* Query if KK outputs a sorted matrix. If not, we need to sort it */
971: auto spgemmHandle = pdata->kh.get_spgemm_handle();
972: if (spgemmHandle->get_sort_option() != 1) PetscCallCXX(sort_crs_matrix(csrmatC)); /* sort_option defaults to -1 in KK!*/
973: #endif
974: PetscCall(PetscLogGpuTimeEnd());
976: PetscCallCXX(ckok = new Mat_SeqAIJKokkos(csrmatC));
977: PetscCall(MatSetSeqAIJKokkosWithCSRMatrix(C, ckok));
978: C->product->destroy = MatProductCtxDestroy_SeqAIJKokkos;
979: PetscFunctionReturn(PETSC_SUCCESS);
980: }
982: /* These are used by the mat-mat operations with dense matrices, which are stored column-major, so their arrays are wrapped in LayoutLeft views.
983: The PetscScalarKokkosView2D types in kokkosimpl.hpp are LayoutRight and thus can not be used here.
984: */
985: using MatScalarKokkosDenseView = Kokkos::View<PetscScalar **, Kokkos::LayoutLeft, DefaultMemorySpace, Kokkos::MemoryTraits<Kokkos::Unmanaged>>;
986: using ConstMatScalarKokkosDenseView = Kokkos::View<const PetscScalar **, Kokkos::LayoutLeft, DefaultMemorySpace, Kokkos::MemoryTraits<Kokkos::Unmanaged>>;
987: using MatScalarKokkosDenseWorkView = Kokkos::View<PetscScalar **, Kokkos::LayoutLeft, DefaultMemorySpace>;
989: /* Context for products with a dense B. Bwork and Cwork are only allocated when B's or C's array is
990: not accessible by Kokkos.
991: */
992: struct MatProductCtx_SeqAIJKokkosDense {
993: MatScalarKokkosDenseWorkView Bwork, Cwork;
994: };
996: static PetscErrorCode MatProductCtxDestroy_SeqAIJKokkosDense(PetscCtxRt pdata)
997: {
998: PetscFunctionBegin;
999: delete *reinterpret_cast<MatProductCtx_SeqAIJKokkosDense **>(pdata);
1000: PetscFunctionReturn(PETSC_SUCCESS);
1001: }
1003: /* C = op(A) B, with A of type MATSEQAIJKOKKOS and B, C dense. */
1004: static PetscErrorCode MatProductNumeric_SeqAIJKokkos_SeqDense(Mat C)
1005: {
1006: Mat_Product *product = C->product;
1007: Mat A, B;
1008: Mat_SeqAIJKokkos *akok;
1009: MatProductCtx_SeqAIJKokkosDense *pdata;
1010: KokkosCsrMatrix csrmat;
1011: ConstMatScalarKokkosDenseView bview, bsub;
1012: MatScalarKokkosDenseView cview, csub;
1013: const PetscScalar *barray;
1014: PetscScalar *carray;
1015: PetscMemType bmtype, cmtype;
1016: const char *mode;
1017: PetscInt m, n, k, blda, clda;
1018: auto exec = PetscGetKokkosExecutionSpace();
1020: PetscFunctionBegin;
1021: MatCheckProduct(C, 1);
1022: PetscCheck(product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data empty");
1023: pdata = static_cast<MatProductCtx_SeqAIJKokkosDense *>(product->data);
1024: A = product->A;
1025: B = product->B;
1026: PetscCall(MatSeqAIJKokkosSyncDevice(A));
1027: akok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1028: switch (product->type) {
1029: case MATPRODUCT_AB:
1030: csrmat = akok->csrmat;
1031: mode = "N";
1032: m = A->rmap->n;
1033: break;
1034: case MATPRODUCT_AtB:
1035: if (A->form_explicit_transpose) {
1036: PetscCall(MatSeqAIJKokkosGenerateTranspose_Private(A, &csrmat));
1037: mode = "N";
1038: } else {
1039: csrmat = akok->csrmat;
1040: mode = "T";
1041: }
1042: m = A->cmap->n;
1043: break;
1044: default:
1045: SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Unsupported product type %s", MatProductTypes[product->type]);
1046: }
1047: k = B->rmap->n;
1048: n = B->cmap->n;
1049: if (!m || !n) PetscFunctionReturn(PETSC_SUCCESS);
1051: PetscCall(MatDenseGetArrayReadAndMemType(B, &barray, &bmtype));
1052: PetscCall(MatDenseGetLDA(B, &blda));
1053: PetscCall(MatDenseGetArrayWriteAndMemType(C, &carray, &cmtype));
1054: PetscCall(MatDenseGetLDA(C, &clda));
1056: /* An array is directly usable by Kokkos when its memory type is PETSC_MEMTYPE_KOKKOS, which is
1057: PETSC_MEMTYPE_HOST in a host-only Kokkos build. Otherwise the array is staged through a device
1058: workspace with a single contiguous copy that stops after the active rows of the last column,
1059: since the tail of the last column may lie beyond the parent allocation when the matrix is a
1060: row-restricted submatrix from MatDenseGetSubMatrix(). C is copied in only when clda > m, to
1061: round-trip the padding rows of the leading columns; the spmv overwrites rows [0, m).
1062: */
1063: if (bmtype == PETSC_MEMTYPE_KOKKOS) {
1064: PetscCallCXX(bview = ConstMatScalarKokkosDenseView(barray, blda, n));
1065: } else {
1066: const PetscInt bcnt = (n - 1) * blda + k;
1068: if (pdata->Bwork.extent(0) != (size_t)blda || pdata->Bwork.extent(1) != (size_t)n) PetscCallCXX(pdata->Bwork = MatScalarKokkosDenseWorkView(NoInit("Bwork"), blda, n));
1069: PetscCallCXX(Kokkos::deep_copy(PetscScalarKokkosView(pdata->Bwork.data(), bcnt), ConstPetscScalarKokkosViewHost(barray, bcnt)));
1070: PetscCall(PetscLogCpuToGpu(sizeof(PetscScalar) * bcnt));
1071: PetscCallCXX(bview = pdata->Bwork);
1072: }
1073: if (cmtype == PETSC_MEMTYPE_KOKKOS) {
1074: PetscCallCXX(cview = MatScalarKokkosDenseView(carray, clda, n));
1075: } else {
1076: const PetscInt ccnt = (n - 1) * clda + m;
1078: if (pdata->Cwork.extent(0) != (size_t)clda || pdata->Cwork.extent(1) != (size_t)n) PetscCallCXX(pdata->Cwork = MatScalarKokkosDenseWorkView(NoInit("Cwork"), clda, n));
1079: if (clda > m) {
1080: PetscCallCXX(Kokkos::deep_copy(PetscScalarKokkosView(pdata->Cwork.data(), ccnt), ConstPetscScalarKokkosViewHost(carray, ccnt)));
1081: PetscCall(PetscLogCpuToGpu(sizeof(PetscScalar) * ccnt));
1082: }
1083: PetscCallCXX(cview = pdata->Cwork);
1084: }
1085: PetscCallCXX(bsub = Kokkos::subview(bview, Kokkos::pair<PetscInt, PetscInt>(0, k), Kokkos::ALL()));
1086: PetscCallCXX(csub = Kokkos::subview(cview, Kokkos::pair<PetscInt, PetscInt>(0, m), Kokkos::ALL()));
1088: PetscCall(PetscLogGpuTimeBegin());
1089: PetscCallCXX(KokkosSparse::spmv(exec, mode, 1.0 /*alpha*/, csrmat, bsub, 0.0 /*beta*/, csub)); /* C = alpha op(A) B + beta C */
1090: PetscCall(PetscLogGpuTimeEnd());
1091: PetscCall(PetscLogGpuFlops(2.0 * csrmat.nnz() * n));
1093: if (cmtype != PETSC_MEMTYPE_KOKKOS) { /* bring the result back to C's host array */
1094: const PetscInt ccnt = (n - 1) * clda + m;
1096: PetscCallCXX(Kokkos::deep_copy(PetscScalarKokkosViewHost(carray, ccnt), ConstPetscScalarKokkosView(pdata->Cwork.data(), ccnt))); /* fences, so the host array is complete before it is restored */
1097: PetscCall(PetscLogGpuToCpu(sizeof(PetscScalar) * ccnt));
1098: }
1099: PetscCall(MatDenseRestoreArrayReadAndMemType(B, &barray));
1100: PetscCall(MatDenseRestoreArrayWriteAndMemType(C, &carray));
1101: PetscFunctionReturn(PETSC_SUCCESS);
1102: }
1104: static PetscErrorCode MatProductSymbolic_SeqAIJKokkos_SeqDense(Mat C)
1105: {
1106: Mat_Product *product = C->product;
1107: Mat A, B;
1108: PetscBool cisdense;
1109: PetscInt m, n;
1111: PetscFunctionBegin;
1112: MatCheckProduct(C, 1);
1113: PetscCheck(!product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data not empty");
1114: A = product->A;
1115: B = product->B;
1116: switch (product->type) {
1117: case MATPRODUCT_AB:
1118: m = A->rmap->n;
1119: n = B->cmap->n;
1120: PetscCall(MatSetBlockSizesFromMats(C, A, B));
1121: break;
1122: case MATPRODUCT_AtB:
1123: m = A->cmap->n;
1124: n = B->cmap->n;
1125: if (A->cmap->bs > 0) PetscCall(PetscLayoutSetBlockSize(C->rmap, A->cmap->bs));
1126: if (B->cmap->bs > 0) PetscCall(PetscLayoutSetBlockSize(C->cmap, B->cmap->bs));
1127: break;
1128: default:
1129: SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Unsupported product type %s", MatProductTypes[product->type]);
1130: }
1131: PetscCall(MatSetSizes(C, m, n, m, n));
1132: PetscCall(PetscObjectBaseTypeCompare((PetscObject)C, MATSEQDENSE, &cisdense));
1133: if (!cisdense) {
1134: PetscCall(MatSetType(C, ((PetscObject)B)->type_name));
1135: PetscCall(MatSetVecType(C, B->defaultvectype));
1136: }
1137: PetscCall(MatSetUp(C));
1139: PetscCallCXX(product->data = new MatProductCtx_SeqAIJKokkosDense());
1140: product->destroy = MatProductCtxDestroy_SeqAIJKokkosDense;
1141: C->ops->productnumeric = MatProductNumeric_SeqAIJKokkos_SeqDense;
1142: PetscFunctionReturn(PETSC_SUCCESS);
1143: }
1145: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_SeqAIJ_SeqDense(Mat);
1147: /* handles sparse matrix matrix ops */
1148: static PetscErrorCode MatProductSetFromOptions_SeqAIJKokkos(Mat mat)
1149: {
1150: Mat_Product *product = mat->product;
1151: PetscBool Bisdense = PETSC_FALSE, Biskok = PETSC_FALSE, Ciskok = PETSC_TRUE;
1153: PetscFunctionBegin;
1154: MatCheckProduct(mat, 1);
1155: PetscCall(PetscObjectBaseTypeCompare((PetscObject)product->B, MATSEQDENSE, &Bisdense));
1156: if (Bisdense) {
1157: switch (product->type) {
1158: case MATPRODUCT_AB:
1159: case MATPRODUCT_AtB:
1160: mat->ops->productsymbolic = MatProductSymbolic_SeqAIJKokkos_SeqDense;
1161: break;
1162: default: /* ABt, PtAP and RARt use the CPU kernels, which sync A's values to host via MatSeqAIJGetArrayRead() */
1163: PetscCall(MatProductSetFromOptions_SeqAIJ_SeqDense(mat));
1164: break;
1165: }
1166: PetscFunctionReturn(PETSC_SUCCESS);
1167: }
1168: PetscCall(PetscObjectTypeCompare((PetscObject)product->B, MATSEQAIJKOKKOS, &Biskok));
1169: if (product->type == MATPRODUCT_ABC) PetscCall(PetscObjectTypeCompare((PetscObject)product->C, MATSEQAIJKOKKOS, &Ciskok));
1170: if (Biskok && Ciskok) {
1171: switch (product->type) {
1172: case MATPRODUCT_AB:
1173: case MATPRODUCT_AtB:
1174: case MATPRODUCT_ABt:
1175: mat->ops->productsymbolic = MatProductSymbolic_SeqAIJKokkos_SeqAIJKokkos;
1176: break;
1177: case MATPRODUCT_PtAP:
1178: case MATPRODUCT_RARt:
1179: case MATPRODUCT_ABC:
1180: mat->ops->productsymbolic = MatProductSymbolic_ABC_Basic;
1181: break;
1182: default:
1183: break;
1184: }
1185: } else { /* fallback for AIJ */
1186: PetscCall(MatProductSetFromOptions_SeqAIJ(mat));
1187: }
1188: PetscFunctionReturn(PETSC_SUCCESS);
1189: }
1191: static PetscErrorCode MatScale_SeqAIJKokkos(Mat A, PetscScalar a)
1192: {
1193: Mat_SeqAIJKokkos *aijkok;
1195: PetscFunctionBegin;
1196: PetscCall(PetscLogGpuTimeBegin());
1197: PetscCall(MatSeqAIJKokkosSyncDevice(A));
1198: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1199: KokkosBlas::scal(PetscGetKokkosExecutionSpace(), aijkok->a_dual.view_device(), a, aijkok->a_dual.view_device());
1200: PetscCall(MatSeqAIJKokkosModifyDevice(A));
1201: PetscCall(PetscLogGpuFlops(aijkok->a_dual.extent(0)));
1202: PetscCall(PetscLogGpuTimeEnd());
1203: PetscFunctionReturn(PETSC_SUCCESS);
1204: }
1206: // add a to A's diagonal (if A is square) or main diagonal (if A is rectangular)
1207: static PetscErrorCode MatShift_SeqAIJKokkos(Mat A, PetscScalar a)
1208: {
1209: PetscBool diagDense = PETSC_FALSE;
1211: PetscFunctionBegin;
1212: // ask for diagDense rather than reading the field, which is only set on demand
1213: if (A->assembled) PetscCall(MatGetDiagonalMarkers_SeqAIJ(A, NULL, &diagDense));
1214: if (diagDense) { // no missing diagonals
1215: PetscInt n = PetscMin(A->rmap->n, A->cmap->n);
1217: PetscCall(PetscLogGpuTimeBegin());
1218: PetscCall(MatSeqAIJKokkosSyncDevice(A));
1219: const auto aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1220: const auto &Aa = aijkok->a_dual.view_device();
1221: const auto &Adiag = aijkok->diag_dual.view_device();
1222: PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, n), KOKKOS_LAMBDA(const PetscInt i) { Aa(Adiag(i)) += a; }));
1223: PetscCall(MatSeqAIJKokkosModifyDevice(A));
1224: PetscCall(PetscLogGpuFlops(n));
1225: PetscCall(PetscLogGpuTimeEnd());
1226: } else { // need reassembly, very slow!
1227: PetscCall(MatShift_Basic(A, a));
1228: }
1229: PetscFunctionReturn(PETSC_SUCCESS);
1230: }
1232: static PetscErrorCode MatDiagonalSet_SeqAIJKokkos(Mat Y, Vec D, InsertMode is)
1233: {
1234: PetscBool diagDense = PETSC_FALSE;
1236: PetscFunctionBegin;
1237: // ask for diagDense rather than reading the field, which is only set on demand
1238: if (Y->assembled) PetscCall(MatGetDiagonalMarkers_SeqAIJ(Y, NULL, &diagDense));
1239: if (diagDense) { // no missing diagonals
1240: ConstPetscScalarKokkosView dv;
1241: PetscInt n, nv;
1243: PetscCall(PetscLogGpuTimeBegin());
1244: PetscCall(MatSeqAIJKokkosSyncDevice(Y));
1245: PetscCall(VecGetKokkosView(D, &dv));
1246: PetscCall(VecGetLocalSize(D, &nv));
1247: n = PetscMin(Y->rmap->n, Y->cmap->n);
1248: PetscCheck(n == nv, PetscObjectComm((PetscObject)Y), PETSC_ERR_ARG_SIZ, "Matrix size and vector size do not match");
1250: const auto aijkok = static_cast<Mat_SeqAIJKokkos *>(Y->spptr);
1251: const auto &Aa = aijkok->a_dual.view_device();
1252: const auto &Adiag = aijkok->diag_dual.view_device();
1253: PetscCallCXX(Kokkos::parallel_for(
1254: Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, n), KOKKOS_LAMBDA(const PetscInt i) {
1255: if (is == INSERT_VALUES) Aa(Adiag(i)) = dv(i);
1256: else Aa(Adiag(i)) += dv(i);
1257: }));
1258: PetscCall(VecRestoreKokkosView(D, &dv));
1259: PetscCall(MatSeqAIJKokkosModifyDevice(Y));
1260: PetscCall(PetscLogGpuFlops(n));
1261: PetscCall(PetscLogGpuTimeEnd());
1262: } else { // need reassembly, very slow!
1263: PetscCall(MatDiagonalSet_Default(Y, D, is));
1264: }
1265: PetscFunctionReturn(PETSC_SUCCESS);
1266: }
1268: static PetscErrorCode MatDiagonalScale_SeqAIJKokkos(Mat A, Vec ll, Vec rr)
1269: {
1270: Mat_SeqAIJ *aijseq = static_cast<Mat_SeqAIJ *>(A->data);
1271: PetscInt m = A->rmap->n, n = A->cmap->n, nz = aijseq->nz;
1272: ConstPetscScalarKokkosView lv, rv;
1274: PetscFunctionBegin;
1275: PetscCall(PetscLogGpuTimeBegin());
1276: PetscCall(MatSeqAIJKokkosSyncDevice(A));
1277: const auto aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1278: const auto &Aa = aijkok->a_dual.view_device();
1279: const auto &Ai = aijkok->i_dual.view_device();
1280: const auto &Aj = aijkok->j_dual.view_device();
1281: if (ll) {
1282: PetscCall(VecGetLocalSize(ll, &m));
1283: PetscCheck(m == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Left scaling vector wrong length");
1284: PetscCall(VecGetKokkosView(ll, &lv));
1285: PetscCallCXX(Kokkos::parallel_for( // for each row
1286: Kokkos::TeamPolicy<>(PetscGetKokkosExecutionSpace(), m, Kokkos::AUTO()), KOKKOS_LAMBDA(const KokkosTeamMemberType &t) {
1287: PetscInt i = t.league_rank(); // row i
1288: PetscInt len = Ai(i + 1) - Ai(i);
1289: // scale entries on the row
1290: Kokkos::parallel_for(Kokkos::TeamThreadRange(t, len), [&](PetscInt j) { Aa(Ai(i) + j) *= lv(i); });
1291: }));
1292: PetscCall(VecRestoreKokkosView(ll, &lv));
1293: PetscCall(PetscLogGpuFlops(nz));
1294: }
1295: if (rr) {
1296: PetscCall(VecGetLocalSize(rr, &n));
1297: PetscCheck(n == A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Right scaling vector wrong length");
1298: PetscCall(VecGetKokkosView(rr, &rv));
1299: PetscCallCXX(Kokkos::parallel_for( // for each nonzero
1300: Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, nz), KOKKOS_LAMBDA(const PetscInt k) { Aa(k) *= rv(Aj(k)); }));
1301: PetscCall(VecRestoreKokkosView(rr, &lv));
1302: PetscCall(PetscLogGpuFlops(nz));
1303: }
1304: PetscCall(MatSeqAIJKokkosModifyDevice(A));
1305: PetscCall(PetscLogGpuTimeEnd());
1306: PetscFunctionReturn(PETSC_SUCCESS);
1307: }
1309: static PetscErrorCode MatZeroEntries_SeqAIJKokkos(Mat A)
1310: {
1311: Mat_SeqAIJKokkos *aijkok;
1313: PetscFunctionBegin;
1314: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1315: if (aijkok) { /* Only zero the device if data is already there */
1316: KokkosBlas::fill(PetscGetKokkosExecutionSpace(), aijkok->a_dual.view_device(), 0.0);
1317: PetscCall(MatSeqAIJKokkosModifyDevice(A));
1318: } else { /* Might be preallocated but not assembled */
1319: PetscCall(MatZeroEntries_SeqAIJ(A));
1320: }
1321: PetscFunctionReturn(PETSC_SUCCESS);
1322: }
1324: static PetscErrorCode MatGetDiagonal_SeqAIJKokkos(Mat A, Vec x)
1325: {
1326: Mat_SeqAIJKokkos *aijkok;
1327: PetscInt n;
1328: PetscScalarKokkosView xv;
1330: PetscFunctionBegin;
1331: PetscCall(VecGetLocalSize(x, &n));
1332: PetscCheck(n == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nonconforming matrix and vector");
1333: PetscCheck(A->factortype == MAT_FACTOR_NONE, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatGetDiagonal_SeqAIJKokkos not supported on factored matrices");
1335: PetscCall(MatSeqAIJKokkosSyncDevice(A));
1336: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1338: const auto &Aa = aijkok->a_dual.view_device();
1339: const auto &Ai = aijkok->i_dual.view_device();
1340: const auto &Adiag = aijkok->diag_dual.view_device();
1342: PetscCall(VecGetKokkosViewWrite(x, &xv));
1343: Kokkos::parallel_for(
1344: Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, n), KOKKOS_LAMBDA(const PetscInt i) {
1345: if (Adiag(i) < Ai(i + 1)) xv(i) = Aa(Adiag(i));
1346: else xv(i) = 0;
1347: });
1348: PetscCall(VecRestoreKokkosViewWrite(x, &xv));
1349: PetscFunctionReturn(PETSC_SUCCESS);
1350: }
1352: // Sum of |a_ij|^2 over the nonzeros of A
1353: PetscErrorCode MatSeqAIJKokkosGetFrobeniusSquared_Private(Mat A, PetscReal *sum)
1354: {
1355: MatScalarKokkosView Aa;
1357: PetscFunctionBegin;
1358: PetscCall(MatSeqAIJKokkosSyncDevice(A));
1359: Aa = static_cast<Mat_SeqAIJKokkos *>(A->spptr)->a_dual.view_device();
1360: PetscCallCXX(Kokkos::parallel_reduce("MatNorm_Frobenius", Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, Aa.extent(0)), KOKKOS_LAMBDA(const PetscInt k, PetscReal &update) { update += PetscRealPart(PetscConj(Aa(k)) * Aa(k)); }, *sum));
1361: PetscFunctionReturn(PETSC_SUCCESS);
1362: }
1364: // sum_j |a_ij| over row i of the CSR matrix (ai, aa), computed by the team t
1365: KOKKOS_INLINE_FUNCTION static PetscReal RowAbsSum_Private(const KokkosTeamMemberType &t, const MatRowMapKokkosView &ai, const MatScalarKokkosView &aa, PetscInt i)
1366: {
1367: PetscReal sum = 0.0;
1369: Kokkos::parallel_reduce(Kokkos::TeamThreadRange(t, ai(i), ai(i + 1)), [&](PetscInt k, PetscReal &s) { s += PetscAbsScalar(aa(k)); }, sum);
1370: return sum;
1371: }
1373: // rowsums(i) = sum_j |A_ij| + sum_j |B_ij| for each row i; B is optional and, if given, has the same number of rows as A
1374: PetscErrorCode MatSeqAIJKokkosGetRowAbsSums_Private(Mat A, Mat B, PetscScalarKokkosView &rowsums)
1375: {
1376: PetscInt m = A->rmap->n;
1377: PetscBool hasB = B ? PETSC_TRUE : PETSC_FALSE;
1378: Mat_SeqAIJKokkos *aijkok, *bijkok;
1379: MatScalarKokkosView Aa, Ba;
1380: MatRowMapKokkosView Ai, Bi;
1382: PetscFunctionBegin;
1383: PetscCall(MatSeqAIJKokkosSyncDevice(A));
1384: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1385: Aa = aijkok->a_dual.view_device();
1386: Ai = aijkok->i_dual.view_device();
1387: if (B) {
1388: PetscCall(MatSeqAIJKokkosSyncDevice(B));
1389: bijkok = static_cast<Mat_SeqAIJKokkos *>(B->spptr);
1390: Ba = bijkok->a_dual.view_device();
1391: Bi = bijkok->i_dual.view_device();
1392: }
1393: PetscCallCXX(Kokkos::parallel_for(
1394: "MatGetRowSumAbs", Kokkos::TeamPolicy<>(PetscGetKokkosExecutionSpace(), m, Kokkos::AUTO()), KOKKOS_LAMBDA(const KokkosTeamMemberType &t) {
1395: PetscInt i = t.league_rank(); // row i
1396: PetscReal sum = RowAbsSum_Private(t, Ai, Aa, i) + (hasB ? RowAbsSum_Private(t, Bi, Ba, i) : 0.0);
1398: Kokkos::single(Kokkos::PerTeam(t), [&]() { rowsums(i) = sum; });
1399: }));
1400: PetscFunctionReturn(PETSC_SUCCESS);
1401: }
1403: // Max over rows i of sum_j |A_ij| + sum_j |B_ij|; B is optional and, if given, has the same number of rows as A
1404: PetscErrorCode MatSeqAIJKokkosGetMaxRowAbsSum_Private(Mat A, Mat B, PetscReal *nrm)
1405: {
1406: PetscInt m = A->rmap->n;
1407: PetscBool hasB = B ? PETSC_TRUE : PETSC_FALSE;
1408: Mat_SeqAIJKokkos *aijkok, *bijkok;
1409: MatScalarKokkosView Aa, Ba;
1410: MatRowMapKokkosView Ai, Bi;
1412: PetscFunctionBegin;
1413: *nrm = 0.0;
1414: if (!m) PetscFunctionReturn(PETSC_SUCCESS); // the Max reducer of an empty range is not zero
1415: PetscCall(MatSeqAIJKokkosSyncDevice(A));
1416: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1417: Aa = aijkok->a_dual.view_device();
1418: Ai = aijkok->i_dual.view_device();
1419: if (B) {
1420: PetscCall(MatSeqAIJKokkosSyncDevice(B));
1421: bijkok = static_cast<Mat_SeqAIJKokkos *>(B->spptr);
1422: Ba = bijkok->a_dual.view_device();
1423: Bi = bijkok->i_dual.view_device();
1424: }
1425: PetscCallCXX(Kokkos::parallel_reduce(
1426: "MatNorm_Infinity", Kokkos::TeamPolicy<>(PetscGetKokkosExecutionSpace(), m, Kokkos::AUTO()),
1427: KOKKOS_LAMBDA(const KokkosTeamMemberType &t, PetscReal &update) {
1428: PetscInt i = t.league_rank(); // row i
1429: PetscReal sum = RowAbsSum_Private(t, Ai, Aa, i) + (hasB ? RowAbsSum_Private(t, Bi, Ba, i) : 0.0);
1431: Kokkos::single(Kokkos::PerTeam(t), [&]() {
1432: if (sum > update) update = sum;
1433: });
1434: },
1435: Kokkos::Max<PetscReal>(*nrm)));
1436: PetscFunctionReturn(PETSC_SUCCESS);
1437: }
1439: // colsums(j) = sum_i |A_ij| for each of the A->cmap->n columns of A
1440: PetscErrorCode MatSeqAIJKokkosGetColumnAbsSums_Private(Mat A, PetscScalarKokkosView &colsums)
1441: {
1442: PetscInt n = A->cmap->n;
1443: DefaultExecutionSpace exec = PetscGetKokkosExecutionSpace();
1444: Mat_SeqAIJKokkos *aijkok;
1445: MatScalarKokkosView Aa;
1446: MatColIdxKokkosView Aj;
1447: Kokkos::View<PetscReal *, DefaultMemorySpace> sums;
1449: PetscFunctionBegin;
1450: PetscCall(MatSeqAIJKokkosSyncDevice(A));
1451: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1452: Aa = aijkok->a_dual.view_device();
1453: Aj = aijkok->j_dual.view_device();
1454: // accumulate in PetscReal so that the atomics do not operate on complex values
1455: PetscCallCXX(sums = Kokkos::View<PetscReal *, DefaultMemorySpace>("sums", n));
1456: PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(exec, 0, Aa.extent(0)), KOKKOS_LAMBDA(const PetscInt k) { Kokkos::atomic_add(&sums(Aj(k)), PetscAbsScalar(Aa(k))); }));
1457: PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(exec, 0, n), KOKKOS_LAMBDA(const PetscInt j) { colsums(j) = sums(j); }));
1458: PetscFunctionReturn(PETSC_SUCCESS);
1459: }
1461: static PetscErrorCode MatNorm_SeqAIJKokkos(Mat A, NormType type, PetscReal *nrm)
1462: {
1463: PetscInt nz = static_cast<Mat_SeqAIJ *>(A->data)->nz;
1465: PetscFunctionBegin;
1466: PetscCall(PetscLogGpuTimeBegin());
1467: if (type == NORM_FROBENIUS) {
1468: PetscCall(MatSeqAIJKokkosGetFrobeniusSquared_Private(A, nrm));
1469: *nrm = PetscSqrtReal(*nrm);
1470: PetscCall(PetscLogGpuFlops(2.0 * nz));
1471: } else if (type == NORM_1) {
1472: PetscInt n = A->cmap->n;
1473: PetscScalarKokkosView colsums;
1475: PetscCallCXX(colsums = PetscScalarKokkosView("colsums", n));
1476: PetscCall(MatSeqAIJKokkosGetColumnAbsSums_Private(A, colsums));
1477: *nrm = 0.0;
1478: if (n) PetscCallCXX(Kokkos::parallel_reduce(Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, n), KOKKOS_LAMBDA(const PetscInt j, PetscReal &update) { update = PetscMax(update, PetscRealPart(colsums(j))); }, Kokkos::Max<PetscReal>(*nrm)));
1479: PetscCall(PetscLogGpuFlops(nz));
1480: } else if (type == NORM_INFINITY) {
1481: PetscCall(MatSeqAIJKokkosGetMaxRowAbsSum_Private(A, NULL, nrm));
1482: PetscCall(PetscLogGpuFlops(nz));
1483: } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "No support for two norm");
1484: PetscCall(PetscLogGpuTimeEnd());
1485: PetscFunctionReturn(PETSC_SUCCESS);
1486: }
1488: // For MATMPIAIJKOKKOS, a row spans both the diagonal block A and the off-diagonal block B, so one kernel sums both
1489: PetscErrorCode MatGetRowSumAbs_AIJKokkos(Mat mat, Vec v)
1490: {
1491: Mat A = mat, B = NULL;
1492: PetscInt n;
1493: PetscBool ismpi;
1494: PetscScalarKokkosView vv;
1496: PetscFunctionBegin;
1497: PetscCheck(mat->factortype == MAT_FACTOR_NONE, PETSC_COMM_SELF, PETSC_ERR_SUP, "MatGetRowSumAbs_AIJKokkos not supported on factored matrices");
1498: PetscCall(VecGetLocalSize(v, &n));
1499: PetscCheck(n == mat->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nonconforming matrix and vector");
1500: PetscCall(PetscObjectTypeCompare((PetscObject)mat, MATMPIAIJKOKKOS, &ismpi));
1501: if (ismpi) PetscCall(MatMPIAIJGetSeqAIJ(mat, &A, &B, NULL));
1502: PetscCall(PetscLogGpuTimeBegin());
1503: PetscCall(VecGetKokkosViewWrite(v, &vv));
1504: PetscCall(MatSeqAIJKokkosGetRowAbsSums_Private(A, B, vv));
1505: PetscCall(VecRestoreKokkosViewWrite(v, &vv));
1506: PetscCall(PetscLogGpuTimeEnd());
1507: PetscCall(PetscLogGpuFlops(static_cast<Mat_SeqAIJ *>(A->data)->nz + (B ? static_cast<Mat_SeqAIJ *>(B->data)->nz : 0)));
1508: PetscFunctionReturn(PETSC_SUCCESS);
1509: }
1511: /* Get a Kokkos View from a mat of type MatSeqAIJKokkos */
1512: PetscErrorCode MatSeqAIJGetKokkosView(Mat A, Kokkos::View<const PetscScalar *> *kv)
1513: {
1514: Mat_SeqAIJKokkos *aijkok;
1516: PetscFunctionBegin;
1518: PetscAssertPointer(kv, 2);
1519: PetscCheckTypeName(A, MATSEQAIJKOKKOS);
1520: PetscCall(MatSeqAIJKokkosSyncDevice(A));
1521: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1522: *kv = aijkok->a_dual.view_device();
1523: PetscFunctionReturn(PETSC_SUCCESS);
1524: }
1526: PetscErrorCode MatSeqAIJRestoreKokkosView(Mat A, Kokkos::View<const PetscScalar *> *kv)
1527: {
1528: PetscFunctionBegin;
1530: PetscAssertPointer(kv, 2);
1531: PetscCheckTypeName(A, MATSEQAIJKOKKOS);
1532: PetscFunctionReturn(PETSC_SUCCESS);
1533: }
1535: PetscErrorCode MatSeqAIJGetKokkosView(Mat A, Kokkos::View<PetscScalar *> *kv)
1536: {
1537: Mat_SeqAIJKokkos *aijkok;
1539: PetscFunctionBegin;
1541: PetscAssertPointer(kv, 2);
1542: PetscCheckTypeName(A, MATSEQAIJKOKKOS);
1543: PetscCall(MatSeqAIJKokkosSyncDevice(A));
1544: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1545: *kv = aijkok->a_dual.view_device();
1546: PetscFunctionReturn(PETSC_SUCCESS);
1547: }
1549: PetscErrorCode MatSeqAIJRestoreKokkosView(Mat A, Kokkos::View<PetscScalar *> *kv)
1550: {
1551: PetscFunctionBegin;
1553: PetscAssertPointer(kv, 2);
1554: PetscCheckTypeName(A, MATSEQAIJKOKKOS);
1555: PetscCall(MatSeqAIJKokkosModifyDevice(A));
1556: PetscFunctionReturn(PETSC_SUCCESS);
1557: }
1559: PetscErrorCode MatSeqAIJGetKokkosViewWrite(Mat A, Kokkos::View<PetscScalar *> *kv)
1560: {
1561: Mat_SeqAIJKokkos *aijkok;
1563: PetscFunctionBegin;
1565: PetscAssertPointer(kv, 2);
1566: PetscCheckTypeName(A, MATSEQAIJKOKKOS);
1567: aijkok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1568: *kv = aijkok->a_dual.view_device();
1569: PetscFunctionReturn(PETSC_SUCCESS);
1570: }
1572: PetscErrorCode MatSeqAIJRestoreKokkosViewWrite(Mat A, Kokkos::View<PetscScalar *> *kv)
1573: {
1574: PetscFunctionBegin;
1576: PetscAssertPointer(kv, 2);
1577: PetscCheckTypeName(A, MATSEQAIJKOKKOS);
1578: PetscCall(MatSeqAIJKokkosModifyDevice(A));
1579: PetscFunctionReturn(PETSC_SUCCESS);
1580: }
1582: 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)
1583: {
1584: Mat_SeqAIJKokkos *akok;
1586: PetscFunctionBegin;
1587: PetscCallCXX(akok = new Mat_SeqAIJKokkos(m, n, j_d.extent(0), i_d, j_d, a_d));
1588: PetscCall(MatCreate(comm, A));
1589: PetscCall(MatSetSeqAIJKokkosWithCSRMatrix(*A, akok));
1590: PetscFunctionReturn(PETSC_SUCCESS);
1591: }
1593: /* Computes Y += alpha X */
1594: static PetscErrorCode MatAXPY_SeqAIJKokkos(Mat Y, PetscScalar alpha, Mat X, MatStructure pattern)
1595: {
1596: Mat_SeqAIJ *x = (Mat_SeqAIJ *)X->data, *y = (Mat_SeqAIJ *)Y->data;
1597: Mat_SeqAIJKokkos *xkok, *ykok, *zkok;
1598: ConstMatScalarKokkosView Xa;
1599: MatScalarKokkosView Ya;
1600: auto exec = PetscGetKokkosExecutionSpace();
1602: PetscFunctionBegin;
1603: PetscCheckTypeName(Y, MATSEQAIJKOKKOS);
1604: PetscCheckTypeName(X, MATSEQAIJKOKKOS);
1605: PetscCall(MatSeqAIJKokkosSyncDevice(Y));
1606: PetscCall(MatSeqAIJKokkosSyncDevice(X));
1607: PetscCall(PetscLogGpuTimeBegin());
1609: if (pattern != SAME_NONZERO_PATTERN && x->nz == y->nz) {
1610: PetscBool e;
1611: PetscCall(PetscArraycmp(x->i, y->i, Y->rmap->n + 1, &e));
1612: if (e) {
1613: PetscCall(PetscArraycmp(x->j, y->j, y->nz, &e));
1614: if (e) pattern = SAME_NONZERO_PATTERN;
1615: }
1616: }
1618: /* cusparseDcsrgeam2() computes C = alpha A + beta B. If one knew sparsity pattern of C, one can skip
1619: cusparseScsrgeam2_bufferSizeExt() / cusparseXcsrgeam2Nnz(), and directly call cusparseScsrgeam2().
1620: If X is SUBSET_NONZERO_PATTERN of Y, we could take advantage of this cusparse feature. However,
1621: KokkosSparse::spadd(alpha,A,beta,B,C) has symbolic and numeric phases, MatAXPY does not.
1622: */
1623: ykok = static_cast<Mat_SeqAIJKokkos *>(Y->spptr);
1624: xkok = static_cast<Mat_SeqAIJKokkos *>(X->spptr);
1625: Xa = xkok->a_dual.view_device();
1626: Ya = ykok->a_dual.view_device();
1628: if (pattern == SAME_NONZERO_PATTERN) {
1629: KokkosBlas::axpy(exec, alpha, Xa, Ya);
1630: PetscCall(MatSeqAIJKokkosModifyDevice(Y));
1631: } else if (pattern == SUBSET_NONZERO_PATTERN) {
1632: MatRowMapKokkosView Xi = xkok->i_dual.view_device(), Yi = ykok->i_dual.view_device();
1633: MatColIdxKokkosView Xj = xkok->j_dual.view_device(), Yj = ykok->j_dual.view_device();
1635: Kokkos::parallel_for(
1636: Kokkos::TeamPolicy<>(exec, Y->rmap->n, 1), KOKKOS_LAMBDA(const KokkosTeamMemberType &t) {
1637: PetscInt i = t.league_rank(); // row i
1638: Kokkos::single(Kokkos::PerTeam(t), [=]() {
1639: // Only one thread works in a team
1640: PetscInt p, q = Yi(i);
1641: for (p = Xi(i); p < Xi(i + 1); p++) { // For each nonzero on row i of X,
1642: while (Xj(p) != Yj(q) && q < Yi(i + 1)) q++; // find the matching nonzero on row i of Y.
1643: if (Xj(p) == Yj(q)) { // Found it
1644: Ya(q) += alpha * Xa(p);
1645: q++;
1646: } else {
1647: // If not found, it indicates the input is wrong (X is not a SUBSET_NONZERO_PATTERN of Y).
1648: // Just insert a NaN at the beginning of row i if it is not empty, to make the result wrong.
1649: #if PETSC_PKG_KOKKOS_VERSION_GE(5, 0, 0)
1650: if (Yi(i) != Yi(i + 1)) Ya(Yi(i)) = KokkosKernels::ArithTraits<PetscScalar>::nan();
1651: #elif PETSC_PKG_KOKKOS_VERSION_GE(3, 7, 0)
1652: if (Yi(i) != Yi(i + 1)) Ya(Yi(i)) = Kokkos::ArithTraits<PetscScalar>::nan();
1653: #else
1654: if (Yi(i) != Yi(i + 1)) Ya(Yi(i)) = Kokkos::Experimental::nan("1");
1655: #endif
1656: }
1657: }
1658: });
1659: });
1660: PetscCall(MatSeqAIJKokkosModifyDevice(Y));
1661: } else { // different nonzero patterns
1662: Mat Z;
1663: KokkosCsrMatrix zcsr;
1664: KernelHandle kh;
1665: kh.create_spadd_handle(true); // X, Y are sorted
1666: KokkosSparse::spadd_symbolic(&kh, xkok->csrmat, ykok->csrmat, zcsr);
1667: KokkosSparse::spadd_numeric(&kh, alpha, xkok->csrmat, (PetscScalar)1.0, ykok->csrmat, zcsr);
1668: zkok = new Mat_SeqAIJKokkos(zcsr);
1669: PetscCall(MatCreateSeqAIJKokkosWithCSRMatrix(PETSC_COMM_SELF, zkok, &Z));
1670: PetscCall(MatHeaderReplace(Y, &Z));
1671: kh.destroy_spadd_handle();
1672: }
1673: PetscCall(PetscLogGpuTimeEnd());
1674: PetscCall(PetscLogGpuFlops(xkok->a_dual.extent(0) * 2)); // Because we scaled X and then added it to Y
1675: PetscFunctionReturn(PETSC_SUCCESS);
1676: }
1678: struct MatCOOStruct_SeqAIJKokkos {
1679: PetscCount n;
1680: PetscCount Atot;
1681: PetscInt nz;
1682: PetscCountKokkosView jmap;
1683: PetscCountKokkosView perm;
1685: MatCOOStruct_SeqAIJKokkos(const MatCOOStruct_SeqAIJ *coo_h)
1686: {
1687: nz = coo_h->nz;
1688: n = coo_h->n;
1689: Atot = coo_h->Atot;
1690: jmap = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), PetscCountKokkosViewHost(coo_h->jmap, nz + 1));
1691: perm = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), PetscCountKokkosViewHost(coo_h->perm, Atot));
1692: }
1693: };
1695: static PetscErrorCode MatCOOStructDestroy_SeqAIJKokkos(PetscCtxRt data)
1696: {
1697: PetscFunctionBegin;
1698: PetscCallCXX(delete *static_cast<MatCOOStruct_SeqAIJKokkos **>(data));
1699: PetscFunctionReturn(PETSC_SUCCESS);
1700: }
1702: static PetscErrorCode MatSetPreallocationCOO_SeqAIJKokkos(Mat mat, PetscCount coo_n, PetscInt coo_i[], PetscInt coo_j[])
1703: {
1704: Mat_SeqAIJKokkos *akok;
1705: Mat_SeqAIJ *aseq;
1706: PetscContainer container_h;
1707: MatCOOStruct_SeqAIJ *coo_h;
1708: MatCOOStruct_SeqAIJKokkos *coo_d;
1710: PetscFunctionBegin;
1711: PetscCall(MatSetPreallocationCOO_SeqAIJ(mat, coo_n, coo_i, coo_j));
1712: aseq = static_cast<Mat_SeqAIJ *>(mat->data);
1713: akok = static_cast<Mat_SeqAIJKokkos *>(mat->spptr);
1714: delete akok;
1715: mat->spptr = akok = new Mat_SeqAIJKokkos(mat, mat->rmap->n, mat->cmap->n, aseq, mat->nonzerostate + 1, PETSC_FALSE);
1716: PetscCall(MatZeroEntries_SeqAIJKokkos(mat));
1718: // Copy the COO struct to device
1719: PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", (PetscObject *)&container_h));
1720: PetscCall(PetscContainerGetPointer(container_h, &coo_h));
1721: PetscCallCXX(coo_d = new MatCOOStruct_SeqAIJKokkos(coo_h));
1723: // Put the COO struct in a container and then attach that to the matrix
1724: PetscCall(PetscObjectContainerCompose((PetscObject)mat, "__PETSc_MatCOOStruct_Device", coo_d, MatCOOStructDestroy_SeqAIJKokkos));
1725: PetscFunctionReturn(PETSC_SUCCESS);
1726: }
1728: static PetscErrorCode MatSetValuesCOO_SeqAIJKokkos(Mat A, const PetscScalar v[], InsertMode imode)
1729: {
1730: Kokkos::View<PetscScalar *> Aa;
1731: ConstMatScalarKokkosView kv;
1732: PetscMemType memtype;
1733: PetscContainer container;
1734: MatCOOStruct_SeqAIJKokkos *coo;
1736: PetscFunctionBegin;
1737: PetscCall(MatSeqAIJCheckCOONonzeroState(A));
1738: PetscCall(PetscObjectQuery((PetscObject)A, "__PETSc_MatCOOStruct_Device", (PetscObject *)&container));
1739: PetscCall(PetscContainerGetPointer(container, &coo));
1741: const auto &n = coo->n;
1742: const auto &Annz = coo->nz;
1743: const auto &jmap = coo->jmap;
1744: const auto &perm = coo->perm;
1746: PetscCall(PetscGetMemType(v, &memtype));
1747: if (PetscMemTypeHost(memtype)) { /* If user gave v[] in host, we might need to copy it to device if any */
1748: kv = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), ConstMatScalarKokkosViewHost(v, n));
1749: PetscCall(PetscLogCpuToGpu(n * sizeof(PetscScalar)));
1750: } else {
1751: kv = ConstMatScalarKokkosView(v, n); /* Directly use v[]'s memory */
1752: }
1754: if (imode == INSERT_VALUES) PetscCall(MatSeqAIJGetKokkosViewWrite(A, &Aa)); /* write matrix values */
1755: else PetscCall(MatSeqAIJGetKokkosView(A, &Aa)); /* read & write matrix values */
1757: PetscCall(PetscLogGpuTimeBegin());
1758: Kokkos::parallel_for(
1759: Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, Annz), KOKKOS_LAMBDA(const PetscCount i) {
1760: PetscScalar sum = 0.0;
1761: for (PetscCount k = jmap(i); k < jmap(i + 1); k++) sum += kv(perm(k));
1762: Aa(i) = (imode == INSERT_VALUES ? 0.0 : Aa(i)) + sum;
1763: });
1764: PetscCall(PetscLogGpuTimeEnd());
1766: if (imode == INSERT_VALUES) PetscCall(MatSeqAIJRestoreKokkosViewWrite(A, &Aa));
1767: else PetscCall(MatSeqAIJRestoreKokkosView(A, &Aa));
1768: PetscFunctionReturn(PETSC_SUCCESS);
1769: }
1771: PETSC_INTERN PetscErrorCode MatBindToCPU_SeqAIJKokkos(Mat A, PetscBool flg)
1772: {
1773: PetscFunctionBegin;
1774: PetscCheck(A->boundtocpu == flg, PetscObjectComm((PetscObject)A), PETSC_ERR_SUP, "Changing binding of a MATAIJKOKKOS matrix is not supported yet");
1775: PetscFunctionReturn(PETSC_SUCCESS);
1776: }
1778: static PetscErrorCode MatSetOps_SeqAIJKokkos(Mat A)
1779: {
1780: Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;
1782: PetscFunctionBegin;
1783: A->offloadmask = PETSC_OFFLOAD_KOKKOS; // We do not really use this flag
1784: 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.
1785: A->ops->assemblyend = MatAssemblyEnd_SeqAIJKokkos;
1786: A->ops->destroy = MatDestroy_SeqAIJKokkos;
1787: A->ops->duplicate = MatDuplicate_SeqAIJKokkos;
1788: A->ops->axpy = MatAXPY_SeqAIJKokkos;
1789: A->ops->scale = MatScale_SeqAIJKokkos;
1790: A->ops->zeroentries = MatZeroEntries_SeqAIJKokkos;
1791: A->ops->productsetfromoptions = MatProductSetFromOptions_SeqAIJKokkos;
1792: A->ops->mult = MatMult_SeqAIJKokkos;
1793: A->ops->multadd = MatMultAdd_SeqAIJKokkos;
1794: A->ops->multtranspose = MatMultTranspose_SeqAIJKokkos;
1795: A->ops->multtransposeadd = MatMultTransposeAdd_SeqAIJKokkos;
1796: A->ops->multhermitiantranspose = MatMultHermitianTranspose_SeqAIJKokkos;
1797: A->ops->multhermitiantransposeadd = MatMultHermitianTransposeAdd_SeqAIJKokkos;
1798: A->ops->productnumeric = MatProductNumeric_SeqAIJKokkos_SeqAIJKokkos;
1799: A->ops->transpose = MatTranspose_SeqAIJKokkos;
1800: A->ops->setoption = MatSetOption_SeqAIJKokkos;
1801: A->ops->getdiagonal = MatGetDiagonal_SeqAIJKokkos;
1802: A->ops->shift = MatShift_SeqAIJKokkos;
1803: A->ops->diagonalset = MatDiagonalSet_SeqAIJKokkos;
1804: A->ops->diagonalscale = MatDiagonalScale_SeqAIJKokkos;
1805: A->ops->norm = MatNorm_SeqAIJKokkos;
1806: A->ops->getrowsumabs = MatGetRowSumAbs_AIJKokkos;
1807: A->ops->getcurrentmemtype = MatGetCurrentMemType_SeqAIJKokkos;
1808: A->ops->bindtocpu = MatBindToCPU_SeqAIJKokkos;
1809: a->ops->getarray = MatSeqAIJGetArray_SeqAIJKokkos;
1810: a->ops->restorearray = MatSeqAIJRestoreArray_SeqAIJKokkos;
1811: a->ops->getarrayread = MatSeqAIJGetArrayRead_SeqAIJKokkos;
1812: a->ops->restorearrayread = MatSeqAIJRestoreArrayRead_SeqAIJKokkos;
1813: a->ops->getarraywrite = MatSeqAIJGetArrayWrite_SeqAIJKokkos;
1814: a->ops->restorearraywrite = MatSeqAIJRestoreArrayWrite_SeqAIJKokkos;
1815: a->ops->getcsrandmemtype = MatSeqAIJGetCSRAndMemType_SeqAIJKokkos;
1817: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSetPreallocationCOO_C", MatSetPreallocationCOO_SeqAIJKokkos));
1818: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSetValuesCOO_C", MatSetValuesCOO_SeqAIJKokkos));
1819: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijkokkos_seqdense_C", MatProductSetFromOptions_SeqAIJKokkos));
1820: #if PetscDefined(HAVE_CUDA)
1821: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijkokkos_seqdensecuda_C", MatProductSetFromOptions_SeqAIJKokkos));
1822: #endif
1823: #if PetscDefined(HAVE_HIP)
1824: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijkokkos_seqdensehip_C", MatProductSetFromOptions_SeqAIJKokkos));
1825: #endif
1826: #if PetscDefined(HAVE_HYPRE)
1827: PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_seqaijkokkos_hypre_C", MatConvert_AIJ_HYPRE));
1828: #endif
1829: PetscFunctionReturn(PETSC_SUCCESS);
1830: }
1832: /*
1833: Extract the (prescribled) diagonal blocks of the matrix and then invert them
1835: Input Parameters:
1836: + A - the MATSEQAIJKOKKOS matrix
1837: . bs - block sizes in 'csr' format, i.e., the i-th block has size bs(i+1) - bs(i)
1838: . bs2 - square of block sizes in 'csr' format, i.e., the i-th block should be stored at offset bs2(i) in diagVal[]
1839: . blkMap - map row ids to block ids, i.e., row i belongs to the block blkMap(i)
1840: - work - a pre-allocated work buffer (as big as diagVal) for use by this routine
1842: Output Parameter:
1843: . diagVal - the (pre-allocated) buffer to store the inverted blocks (each block is stored in column-major order)
1844: */
1845: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode MatInvertVariableBlockDiagonal_SeqAIJKokkos(Mat A, const PetscIntKokkosView &bs, const PetscIntKokkosView &bs2, const PetscIntKokkosView &blkMap, PetscScalarKokkosView &work, PetscScalarKokkosView &diagVal)
1846: {
1847: Mat_SeqAIJKokkos *akok = static_cast<Mat_SeqAIJKokkos *>(A->spptr);
1848: PetscInt nblocks = bs.extent(0) - 1;
1850: PetscFunctionBegin;
1851: PetscCall(MatSeqAIJKokkosSyncDevice(A)); // Since we'll access A's value on device
1853: // Pull out the diagonal blocks of the matrix and then invert the blocks
1854: auto Aa = akok->a_dual.view_device();
1855: auto Ai = akok->i_dual.view_device();
1856: auto Aj = akok->j_dual.view_device();
1857: auto Adiag = akok->diag_dual.view_device();
1858: // TODO: how to tune the team size?
1859: #if defined(KOKKOS_ENABLE_UNIFIED_MEMORY)
1860: auto ts = Kokkos::AUTO();
1861: #else
1862: auto ts = 16; // improved performance 30% over Kokkos::AUTO() with CUDA, but failed with "Kokkos::abort: Requested Team Size is too large!" on CPUs
1863: #endif
1864: PetscCallCXX(Kokkos::parallel_for(
1865: Kokkos::TeamPolicy<>(PetscGetKokkosExecutionSpace(), nblocks, ts), KOKKOS_LAMBDA(const KokkosTeamMemberType &teamMember) {
1866: const PetscInt bid = teamMember.league_rank(); // block id
1867: const PetscInt rstart = bs(bid); // this block starts from this row
1868: const PetscInt m = bs(bid + 1) - bs(bid); // size of this block
1869: const auto &B = Kokkos::View<PetscScalar **, Kokkos::LayoutLeft>(&diagVal(bs2(bid)), m, m); // column-major order
1870: const auto &W = PetscScalarKokkosView(&work(bs2(bid)), m * m);
1872: Kokkos::parallel_for(Kokkos::TeamThreadRange(teamMember, m), [=](const PetscInt &r) { // r-th row in B
1873: PetscInt i = rstart + r; // i-th row in A
1875: if (Ai(i) <= Adiag(i) && Adiag(i) < Ai(i + 1)) { // if the diagonal exists (common case)
1876: PetscInt first = Adiag(i) - r; // we start to check nonzeros from here along this row
1878: for (PetscInt c = 0; c < m; c++) { // walk n steps to see what column indices we will meet
1879: 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
1880: B(r, c) = 0.0;
1881: } else if (Aj(first + c) == rstart + c) { // this entry is right on the (rstart+c) column
1882: B(r, c) = Aa(first + c);
1883: } else { // this entry does not show up in the CSR
1884: B(r, c) = 0.0;
1885: }
1886: }
1887: } else { // rare case that the diagonal does not exist
1888: const PetscInt begin = Ai(i);
1889: const PetscInt end = Ai(i + 1);
1890: for (PetscInt c = 0; c < m; c++) B(r, c) = 0.0;
1891: 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.
1892: if (rstart <= Aj(j) && Aj(j) < rstart + m) B(r, Aj(j) - rstart) = Aa(j);
1893: else if (Aj(j) >= rstart + m) break;
1894: }
1895: }
1896: });
1898: // LU-decompose B (w/o pivoting) and then invert B
1899: KokkosBatched::TeamLU<KokkosTeamMemberType, KokkosBatched::Algo::LU::Unblocked>::invoke(teamMember, B, 0.0);
1900: KokkosBatched::TeamInverseLU<KokkosTeamMemberType, KokkosBatched::Algo::InverseLU::Unblocked>::invoke(teamMember, B, W);
1901: }));
1902: // PetscLogGpuFlops() is done in the caller PCSetUp_VPBJacobi_Kokkos as we don't want to compute the flops in kernels
1903: PetscFunctionReturn(PETSC_SUCCESS);
1904: }
1906: PETSC_INTERN PetscErrorCode MatSetSeqAIJKokkosWithCSRMatrix(Mat A, Mat_SeqAIJKokkos *akok)
1907: {
1908: Mat_SeqAIJ *aseq;
1909: PetscInt i, m, n;
1910: auto exec = PetscGetKokkosExecutionSpace();
1912: PetscFunctionBegin;
1913: PetscCheck(!A->spptr, PETSC_COMM_SELF, PETSC_ERR_PLIB, "A->spptr is supposed to be empty");
1915: m = akok->nrows();
1916: n = akok->ncols();
1917: PetscCall(MatSetSizes(A, m, n, m, n));
1918: PetscCall(MatSetType(A, MATSEQAIJKOKKOS));
1920: /* Set up data structures of A as a MATSEQAIJ */
1921: PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(A, MAT_SKIP_ALLOCATION, NULL));
1922: aseq = (Mat_SeqAIJ *)A->data;
1924: PetscCall(KokkosDualViewSyncHost(akok->i_dual, exec)); /* We always need sync'ed i, j on host */
1925: PetscCall(KokkosDualViewSyncHost(akok->j_dual, exec));
1927: aseq->i = akok->i_host_data();
1928: aseq->j = akok->j_host_data();
1929: aseq->a = akok->a_host_data();
1930: aseq->nonew = -1; /*this indicates that inserting a new value in the matrix that generates a new nonzero is an error*/
1931: aseq->free_a = PETSC_FALSE;
1932: aseq->free_ij = PETSC_FALSE;
1933: aseq->nz = akok->nnz();
1934: aseq->maxnz = aseq->nz;
1936: PetscCall(PetscMalloc1(m, &aseq->imax));
1937: PetscCall(PetscMalloc1(m, &aseq->ilen));
1938: for (i = 0; i < m; i++) aseq->ilen[i] = aseq->imax[i] = aseq->i[i + 1] - aseq->i[i];
1940: /* It is critical to set the nonzerostate, as we use it to check if sparsity pattern (hence data) has changed on host in MatAssemblyEnd */
1941: akok->nonzerostate = A->nonzerostate;
1942: A->spptr = akok; /* Set A->spptr before MatAssembly so that A->spptr won't be allocated again there */
1943: PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
1944: PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
1945: PetscFunctionReturn(PETSC_SUCCESS);
1946: }
1948: PETSC_INTERN PetscErrorCode MatSeqAIJKokkosGetKokkosCsrMatrix(Mat A, KokkosCsrMatrix *csr)
1949: {
1950: PetscFunctionBegin;
1951: PetscCall(MatSeqAIJKokkosSyncDevice(A));
1952: *csr = static_cast<Mat_SeqAIJKokkos *>(A->spptr)->csrmat;
1953: PetscFunctionReturn(PETSC_SUCCESS);
1954: }
1956: PETSC_INTERN PetscErrorCode MatCreateSeqAIJKokkosWithKokkosCsrMatrix(MPI_Comm comm, KokkosCsrMatrix csr, Mat *A)
1957: {
1958: Mat_SeqAIJKokkos *akok;
1960: PetscFunctionBegin;
1961: PetscCallCXX(akok = new Mat_SeqAIJKokkos(csr));
1962: PetscCall(MatCreate(comm, A));
1963: PetscCall(MatSetSeqAIJKokkosWithCSRMatrix(*A, akok));
1964: PetscFunctionReturn(PETSC_SUCCESS);
1965: }
1967: /* Crete a SEQAIJKOKKOS matrix with a Mat_SeqAIJKokkos data structure
1969: Note we have names like MatSeqAIJSetPreallocationCSR, so I use capitalized CSR
1970: */
1971: PETSC_INTERN PetscErrorCode MatCreateSeqAIJKokkosWithCSRMatrix(MPI_Comm comm, Mat_SeqAIJKokkos *akok, Mat *A)
1972: {
1973: PetscFunctionBegin;
1974: PetscCall(MatCreate(comm, A));
1975: PetscCall(MatSetSeqAIJKokkosWithCSRMatrix(*A, akok));
1976: PetscFunctionReturn(PETSC_SUCCESS);
1977: }
1979: /*@
1980: MatCreateSeqAIJKokkos - Creates a sparse matrix in `MATSEQAIJKOKKOS` (compressed row) format
1981: (the default parallel PETSc format). This matrix will ultimately be handled by
1982: Kokkos for calculations.
1984: Collective
1986: Input Parameters:
1987: + comm - MPI communicator, set to `PETSC_COMM_SELF`
1988: . m - number of rows
1989: . n - number of columns
1990: . nz - number of nonzeros per row (same for all rows), ignored if `nnz` is provided
1991: - nnz - array containing the number of nonzeros in the various rows (possibly different for each row) or `NULL`
1993: Output Parameter:
1994: . A - the matrix
1996: Level: intermediate
1998: Notes:
1999: It is recommended that one use the `MatCreate()`, `MatSetType()` and/or `MatSetFromOptions()`,
2000: MatXXXXSetPreallocation() paradgm instead of this routine directly.
2001: [MatXXXXSetPreallocation() is, for example, `MatSeqAIJSetPreallocation()`]
2003: The AIJ format, also called
2004: compressed row storage, is fully compatible with standard Fortran
2005: storage. That is, the stored row and column indices can begin at
2006: either one (as in Fortran) or zero.
2008: Specify the preallocated storage with either `nz` or `nnz` (not both).
2009: Set `nz` = `PETSC_DEFAULT` and `nnz` = `NULL` for PETSc to control dynamic memory
2010: allocation.
2012: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateAIJ()`, `MatSetValues()`, `MatSeqAIJSetColumnIndices()`, `MatCreateSeqAIJWithArrays()`
2013: @*/
2014: PetscErrorCode MatCreateSeqAIJKokkos(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt nz, const PetscInt nnz[], Mat *A)
2015: {
2016: PetscFunctionBegin;
2017: PetscCall(PetscKokkosInitializeCheck());
2018: PetscCall(MatCreate(comm, A));
2019: PetscCall(MatSetSizes(*A, m, n, m, n));
2020: PetscCall(MatSetType(*A, MATSEQAIJKOKKOS));
2021: PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(*A, nz, (PetscInt *)nnz));
2022: PetscFunctionReturn(PETSC_SUCCESS);
2023: }
2025: // After matrix numeric factorization, there are still steps to do before triangular solve can be called.
2026: // 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).
2027: // In cusparse, one has to call cusparseSpSV_analysis() with updated triangular matrix values before calling cusparseSpSV_solve().
2028: // Simiarily, in KK sptrsv_symbolic() has to be called before sptrsv_solve(). We put these steps in MatSeqAIJKokkos{Transpose}SolveCheck.
2029: static PetscErrorCode MatSeqAIJKokkosSolveCheck(Mat A)
2030: {
2031: Mat_SeqAIJKokkosTriFactors *factors = (Mat_SeqAIJKokkosTriFactors *)A->spptr;
2032: const PetscBool has_lower = factors->iL_d.extent(0) ? PETSC_TRUE : PETSC_FALSE; // false with Choleksy
2033: const PetscBool has_upper = factors->iU_d.extent(0) ? PETSC_TRUE : PETSC_FALSE; // true with LU and Choleksy
2035: PetscFunctionBegin;
2036: if (!factors->sptrsv_symbolic_completed) { // If sptrsv_symbolic was not called yet
2037: if (has_upper) PetscCallCXX(sptrsv_symbolic(&factors->khU, factors->iU_d, factors->jU_d, factors->aU_d));
2038: if (has_lower) PetscCallCXX(sptrsv_symbolic(&factors->khL, factors->iL_d, factors->jL_d, factors->aL_d));
2039: factors->sptrsv_symbolic_completed = PETSC_TRUE;
2040: }
2041: PetscFunctionReturn(PETSC_SUCCESS);
2042: }
2044: static PetscErrorCode MatSeqAIJKokkosTransposeSolveCheck(Mat A)
2045: {
2046: const PetscInt n = A->rmap->n;
2047: Mat_SeqAIJKokkosTriFactors *factors = (Mat_SeqAIJKokkosTriFactors *)A->spptr;
2048: const PetscBool has_lower = factors->iL_d.extent(0) ? PETSC_TRUE : PETSC_FALSE; // false with Choleksy
2049: const PetscBool has_upper = factors->iU_d.extent(0) ? PETSC_TRUE : PETSC_FALSE; // true with LU or Choleksy
2051: PetscFunctionBegin;
2052: if (!factors->transpose_updated) {
2053: if (has_upper) {
2054: if (!factors->iUt_d.extent(0)) { // Allocate Ut on device if not yet
2055: factors->iUt_d = MatRowMapKokkosView("factors->iUt_d", n + 1); // KK requires this view to be initialized to 0 to call transpose_matrix
2056: factors->jUt_d = MatColIdxKokkosView(NoInit("factors->jUt_d"), factors->jU_d.extent(0));
2057: factors->aUt_d = MatScalarKokkosView(NoInit("factors->aUt_d"), factors->aU_d.extent(0));
2058: }
2060: if (factors->iU_h.extent(0)) { // If U is on host (factorization was done on host), we also compute the transpose on host
2061: if (!factors->U) {
2062: Mat_SeqAIJ *seq;
2064: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, n, n, factors->iU_h.data(), factors->jU_h.data(), factors->aU_h.data(), &factors->U));
2065: PetscCall(MatTranspose(factors->U, MAT_INITIAL_MATRIX, &factors->Ut));
2067: seq = static_cast<Mat_SeqAIJ *>(factors->Ut->data);
2068: factors->iUt_h = MatRowMapKokkosViewHost(seq->i, n + 1);
2069: factors->jUt_h = MatColIdxKokkosViewHost(seq->j, seq->nz);
2070: factors->aUt_h = MatScalarKokkosViewHost(seq->a, seq->nz);
2071: } else {
2072: PetscCall(MatTranspose(factors->U, MAT_REUSE_MATRIX, &factors->Ut)); // Matrix Ut' data is aliased with {i, j, a}Ut_h
2073: }
2074: // Copy Ut from host to device
2075: PetscCallCXX(Kokkos::deep_copy(factors->iUt_d, factors->iUt_h));
2076: PetscCallCXX(Kokkos::deep_copy(factors->jUt_d, factors->jUt_h));
2077: PetscCallCXX(Kokkos::deep_copy(factors->aUt_d, factors->aUt_h));
2078: } else { // If U was computed on device, we also compute the transpose there
2079: // 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.
2080: PetscCallCXX(transpose_matrix<ConstMatRowMapKokkosView, ConstMatColIdxKokkosView, ConstMatScalarKokkosView, MatRowMapKokkosView, MatColIdxKokkosView, MatScalarKokkosView, MatRowMapKokkosView, DefaultExecutionSpace>(n, n, factors->iU_d,
2081: factors->jU_d, factors->aU_d,
2082: factors->iUt_d, factors->jUt_d,
2083: factors->aUt_d));
2084: PetscCallCXX(sort_crs_matrix<DefaultExecutionSpace, MatRowMapKokkosView, MatColIdxKokkosView, MatScalarKokkosView>(factors->iUt_d, factors->jUt_d, factors->aUt_d));
2085: }
2086: PetscCallCXX(sptrsv_symbolic(&factors->khUt, factors->iUt_d, factors->jUt_d, factors->aUt_d));
2087: }
2089: // do the same for L with LU
2090: if (has_lower) {
2091: if (!factors->iLt_d.extent(0)) { // Allocate Lt on device if not yet
2092: factors->iLt_d = MatRowMapKokkosView("factors->iLt_d", n + 1); // KK requires this view to be initialized to 0 to call transpose_matrix
2093: factors->jLt_d = MatColIdxKokkosView(NoInit("factors->jLt_d"), factors->jL_d.extent(0));
2094: factors->aLt_d = MatScalarKokkosView(NoInit("factors->aLt_d"), factors->aL_d.extent(0));
2095: }
2097: if (factors->iL_h.extent(0)) { // If L is on host, we also compute the transpose on host
2098: if (!factors->L) {
2099: Mat_SeqAIJ *seq;
2101: PetscCall(MatCreateSeqAIJWithArrays(PETSC_COMM_SELF, n, n, factors->iL_h.data(), factors->jL_h.data(), factors->aL_h.data(), &factors->L));
2102: PetscCall(MatTranspose(factors->L, MAT_INITIAL_MATRIX, &factors->Lt));
2104: seq = static_cast<Mat_SeqAIJ *>(factors->Lt->data);
2105: factors->iLt_h = MatRowMapKokkosViewHost(seq->i, n + 1);
2106: factors->jLt_h = MatColIdxKokkosViewHost(seq->j, seq->nz);
2107: factors->aLt_h = MatScalarKokkosViewHost(seq->a, seq->nz);
2108: } else {
2109: PetscCall(MatTranspose(factors->L, MAT_REUSE_MATRIX, &factors->Lt)); // Matrix Lt' data is aliased with {i, j, a}Lt_h
2110: }
2111: // Copy Lt from host to device
2112: PetscCallCXX(Kokkos::deep_copy(factors->iLt_d, factors->iLt_h));
2113: PetscCallCXX(Kokkos::deep_copy(factors->jLt_d, factors->jLt_h));
2114: PetscCallCXX(Kokkos::deep_copy(factors->aLt_d, factors->aLt_h));
2115: } else { // If L was computed on device, we also compute the transpose there
2116: // 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.
2117: PetscCallCXX(transpose_matrix<ConstMatRowMapKokkosView, ConstMatColIdxKokkosView, ConstMatScalarKokkosView, MatRowMapKokkosView, MatColIdxKokkosView, MatScalarKokkosView, MatRowMapKokkosView, DefaultExecutionSpace>(n, n, factors->iL_d,
2118: factors->jL_d, factors->aL_d,
2119: factors->iLt_d, factors->jLt_d,
2120: factors->aLt_d));
2121: PetscCallCXX(sort_crs_matrix<DefaultExecutionSpace, MatRowMapKokkosView, MatColIdxKokkosView, MatScalarKokkosView>(factors->iLt_d, factors->jLt_d, factors->aLt_d));
2122: }
2123: PetscCallCXX(sptrsv_symbolic(&factors->khLt, factors->iLt_d, factors->jLt_d, factors->aLt_d));
2124: }
2126: factors->transpose_updated = PETSC_TRUE;
2127: }
2128: PetscFunctionReturn(PETSC_SUCCESS);
2129: }
2131: // Solve Ax = b, with RAR = U^T D U, where R is the row (and col) permutation matrix on A.
2132: // R is represented by rowperm in factors. If R is identity (i.e, no reordering), then rowperm is empty.
2133: static PetscErrorCode MatSolve_SeqAIJKokkos_Cholesky(Mat A, Vec bb, Vec xx)
2134: {
2135: auto exec = PetscGetKokkosExecutionSpace();
2136: Mat_SeqAIJKokkosTriFactors *factors = (Mat_SeqAIJKokkosTriFactors *)A->spptr;
2137: PetscInt m = A->rmap->n;
2138: PetscScalarKokkosView D = factors->D_d;
2139: PetscScalarKokkosView X, Y, B; // alias
2140: ConstPetscScalarKokkosView b;
2141: PetscScalarKokkosView x;
2142: PetscIntKokkosView &rowperm = factors->rowperm;
2143: PetscBool identity = rowperm.extent(0) ? PETSC_FALSE : PETSC_TRUE;
2145: PetscFunctionBegin;
2146: PetscCall(PetscLogGpuTimeBegin());
2147: PetscCall(MatSeqAIJKokkosSolveCheck(A)); // for UX = T
2148: PetscCall(MatSeqAIJKokkosTransposeSolveCheck(A)); // for U^T Y = B
2149: PetscCall(VecGetKokkosView(bb, &b));
2150: PetscCall(VecGetKokkosViewWrite(xx, &x));
2152: // Solve U^T Y = B
2153: if (identity) { // Reorder b with the row permutation
2154: B = PetscScalarKokkosView(const_cast<PetscScalar *>(b.data()), b.extent(0));
2155: Y = factors->workVector;
2156: } else {
2157: B = factors->workVector;
2158: PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(exec, 0, m), KOKKOS_LAMBDA(const PetscInt i) { B(i) = b(rowperm(i)); }));
2159: Y = x;
2160: }
2161: PetscCallCXX(sptrsv_solve(exec, &factors->khUt, factors->iUt_d, factors->jUt_d, factors->aUt_d, B, Y));
2163: // Solve diag(D) Y' = Y.
2164: // Actually just do Y' = Y*D since D is already inverted in MatCholeskyFactorNumeric_SeqAIJ(). It is basically a vector element-wise multiplication.
2165: PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(exec, 0, m), KOKKOS_LAMBDA(const PetscInt i) { Y(i) = Y(i) * D(i); }));
2167: // Solve UX = Y
2168: if (identity) {
2169: X = x;
2170: } else {
2171: X = factors->workVector; // B is not needed anymore
2172: }
2173: PetscCallCXX(sptrsv_solve(exec, &factors->khU, factors->iU_d, factors->jU_d, factors->aU_d, Y, X));
2175: // Reorder X with the inverse column (row) permutation
2176: if (!identity) PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(exec, 0, m), KOKKOS_LAMBDA(const PetscInt i) { x(rowperm(i)) = X(i); }));
2178: PetscCall(VecRestoreKokkosView(bb, &b));
2179: PetscCall(VecRestoreKokkosViewWrite(xx, &x));
2180: PetscCall(PetscLogGpuTimeEnd());
2181: PetscFunctionReturn(PETSC_SUCCESS);
2182: }
2184: // Solve Ax = b, with RAC = LU, where R and C are row and col permutation matrices on A respectively.
2185: // R and C are represented by rowperm and colperm in factors.
2186: // If R or C is identity (i.e, no reordering), then rowperm or colperm is empty.
2187: static PetscErrorCode MatSolve_SeqAIJKokkos_LU(Mat A, Vec bb, Vec xx)
2188: {
2189: auto exec = PetscGetKokkosExecutionSpace();
2190: Mat_SeqAIJKokkosTriFactors *factors = (Mat_SeqAIJKokkosTriFactors *)A->spptr;
2191: PetscInt m = A->rmap->n;
2192: PetscScalarKokkosView X, Y, B; // alias
2193: ConstPetscScalarKokkosView b;
2194: PetscScalarKokkosView x;
2195: PetscIntKokkosView &rowperm = factors->rowperm;
2196: PetscIntKokkosView &colperm = factors->colperm;
2197: PetscBool row_identity = rowperm.extent(0) ? PETSC_FALSE : PETSC_TRUE;
2198: PetscBool col_identity = colperm.extent(0) ? PETSC_FALSE : PETSC_TRUE;
2200: PetscFunctionBegin;
2201: PetscCall(PetscLogGpuTimeBegin());
2202: PetscCall(MatSeqAIJKokkosSolveCheck(A));
2203: PetscCall(VecGetKokkosView(bb, &b));
2204: PetscCall(VecGetKokkosViewWrite(xx, &x));
2206: // Solve L Y = B (i.e., L (U C^- x) = R b). R b indicates applying the row permutation on b.
2207: if (row_identity) {
2208: B = PetscScalarKokkosView(const_cast<PetscScalar *>(b.data()), b.extent(0));
2209: Y = factors->workVector;
2210: } else {
2211: B = factors->workVector;
2212: PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(exec, 0, m), KOKKOS_LAMBDA(const PetscInt i) { B(i) = b(rowperm(i)); }));
2213: Y = x;
2214: }
2215: PetscCallCXX(sptrsv_solve(exec, &factors->khL, factors->iL_d, factors->jL_d, factors->aL_d, B, Y));
2217: // Solve U C^- x = Y
2218: if (col_identity) {
2219: X = x;
2220: } else {
2221: X = factors->workVector;
2222: }
2223: PetscCallCXX(sptrsv_solve(exec, &factors->khU, factors->iU_d, factors->jU_d, factors->aU_d, Y, X));
2225: // x = C X; Reorder X with the inverse col permutation
2226: if (!col_identity) PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(exec, 0, m), KOKKOS_LAMBDA(const PetscInt i) { x(colperm(i)) = X(i); }));
2228: PetscCall(VecRestoreKokkosView(bb, &b));
2229: PetscCall(VecRestoreKokkosViewWrite(xx, &x));
2230: PetscCall(PetscLogGpuTimeEnd());
2231: PetscFunctionReturn(PETSC_SUCCESS);
2232: }
2234: // Solve A^T x = b, with RAC = LU, where R and C are row and col permutation matrices on A respectively.
2235: // R and C are represented by rowperm and colperm in factors.
2236: // If R or C is identity (i.e, no reordering), then rowperm or colperm is empty.
2237: // 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.
2238: static PetscErrorCode MatSolveTranspose_SeqAIJKokkos_LU(Mat A, Vec bb, Vec xx)
2239: {
2240: auto exec = PetscGetKokkosExecutionSpace();
2241: Mat_SeqAIJKokkosTriFactors *factors = (Mat_SeqAIJKokkosTriFactors *)A->spptr;
2242: PetscInt m = A->rmap->n;
2243: PetscScalarKokkosView X, Y, B; // alias
2244: ConstPetscScalarKokkosView b;
2245: PetscScalarKokkosView x;
2246: PetscIntKokkosView &rowperm = factors->rowperm;
2247: PetscIntKokkosView &colperm = factors->colperm;
2248: PetscBool row_identity = rowperm.extent(0) ? PETSC_FALSE : PETSC_TRUE;
2249: PetscBool col_identity = colperm.extent(0) ? PETSC_FALSE : PETSC_TRUE;
2251: PetscFunctionBegin;
2252: PetscCall(PetscLogGpuTimeBegin());
2253: PetscCall(MatSeqAIJKokkosTransposeSolveCheck(A)); // Update L^T, U^T if needed, and do sptrsv symbolic for L^T, U^T
2254: PetscCall(VecGetKokkosView(bb, &b));
2255: PetscCall(VecGetKokkosViewWrite(xx, &x));
2257: // 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.
2258: if (col_identity) { // Reorder b with the col permutation
2259: B = PetscScalarKokkosView(const_cast<PetscScalar *>(b.data()), b.extent(0));
2260: Y = factors->workVector;
2261: } else {
2262: B = factors->workVector;
2263: PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(exec, 0, m), KOKKOS_LAMBDA(const PetscInt i) { B(i) = b(colperm(i)); }));
2264: Y = x;
2265: }
2266: PetscCallCXX(sptrsv_solve(exec, &factors->khUt, factors->iUt_d, factors->jUt_d, factors->aUt_d, B, Y));
2268: // Solve L^T X = Y
2269: if (row_identity) {
2270: X = x;
2271: } else {
2272: X = factors->workVector;
2273: }
2274: PetscCallCXX(sptrsv_solve(exec, &factors->khLt, factors->iLt_d, factors->jLt_d, factors->aLt_d, Y, X));
2276: // x = R^- X = R^T X; Reorder X with the inverse row permutation
2277: if (!row_identity) PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(exec, 0, m), KOKKOS_LAMBDA(const PetscInt i) { x(rowperm(i)) = X(i); }));
2279: PetscCall(VecRestoreKokkosView(bb, &b));
2280: PetscCall(VecRestoreKokkosViewWrite(xx, &x));
2281: PetscCall(PetscLogGpuTimeEnd());
2282: PetscFunctionReturn(PETSC_SUCCESS);
2283: }
2285: static PetscErrorCode MatLUFactorNumeric_SeqAIJKokkos(Mat B, Mat A, const MatFactorInfo *info)
2286: {
2287: PetscFunctionBegin;
2288: PetscCall(MatSeqAIJKokkosSyncHost(A));
2289: PetscCall(MatLUFactorNumeric_SeqAIJ(B, A, info));
2291: if (!info->solveonhost) { // if solve on host, then we don't need to copy L, U to device
2292: Mat_SeqAIJKokkosTriFactors *factors = (Mat_SeqAIJKokkosTriFactors *)B->spptr;
2293: Mat_SeqAIJ *b = static_cast<Mat_SeqAIJ *>(B->data);
2294: const PetscInt *Bi = b->i, *Bj = b->j, *Bdiag = b->diag;
2295: const MatScalar *Ba = b->a;
2296: PetscInt m = B->rmap->n, n = B->cmap->n;
2298: if (factors->iL_h.extent(0) == 0) { // Allocate memory and copy the L, U structure for the first time
2299: // Allocate memory and copy the structure
2300: factors->iL_h = MatRowMapKokkosViewHost(NoInit("iL_h"), m + 1);
2301: factors->jL_h = MatColIdxKokkosViewHost(NoInit("jL_h"), (Bi[m] - Bi[0]) + m); // + the diagonal entries
2302: factors->aL_h = MatScalarKokkosViewHost(NoInit("aL_h"), (Bi[m] - Bi[0]) + m);
2303: factors->iU_h = MatRowMapKokkosViewHost(NoInit("iU_h"), m + 1);
2304: factors->jU_h = MatColIdxKokkosViewHost(NoInit("jU_h"), Bdiag[0] - Bdiag[m]);
2305: factors->aU_h = MatScalarKokkosViewHost(NoInit("aU_h"), Bdiag[0] - Bdiag[m]);
2307: PetscInt *Li = factors->iL_h.data();
2308: PetscInt *Lj = factors->jL_h.data();
2309: PetscInt *Ui = factors->iU_h.data();
2310: PetscInt *Uj = factors->jU_h.data();
2312: Li[0] = Ui[0] = 0;
2313: for (PetscInt i = 0; i < m; i++) {
2314: PetscInt llen = Bi[i + 1] - Bi[i]; // exclusive of the diagonal entry
2315: PetscInt ulen = Bdiag[i] - Bdiag[i + 1]; // inclusive of the diagonal entry
2317: PetscCall(PetscArraycpy(Lj + Li[i], Bj + Bi[i], llen)); // entries of L on the left of the diagonal
2318: Lj[Li[i] + llen] = i; // diagonal entry of L
2320: Uj[Ui[i]] = i; // diagonal entry of U
2321: PetscCall(PetscArraycpy(Uj + Ui[i] + 1, Bj + Bdiag[i + 1] + 1, ulen - 1)); // entries of U on the right of the diagonal
2323: Li[i + 1] = Li[i] + llen + 1;
2324: Ui[i + 1] = Ui[i] + ulen;
2325: }
2327: factors->iL_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), factors->iL_h);
2328: factors->jL_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), factors->jL_h);
2329: factors->iU_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), factors->iU_h);
2330: factors->jU_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), factors->jU_h);
2331: factors->aL_d = Kokkos::create_mirror_view(DefaultMemorySpace(), factors->aL_h);
2332: factors->aU_d = Kokkos::create_mirror_view(DefaultMemorySpace(), factors->aU_h);
2334: // Copy row/col permutation to device
2335: IS rowperm = ((Mat_SeqAIJ *)B->data)->row;
2336: PetscBool row_identity;
2337: PetscCall(ISIdentity(rowperm, &row_identity));
2338: if (!row_identity) {
2339: const PetscInt *ip;
2341: PetscCall(ISGetIndices(rowperm, &ip));
2342: factors->rowperm = PetscIntKokkosView(NoInit("rowperm"), m);
2343: PetscCallCXX(Kokkos::deep_copy(factors->rowperm, PetscIntKokkosViewHost(const_cast<PetscInt *>(ip), m)));
2344: PetscCall(ISRestoreIndices(rowperm, &ip));
2345: PetscCall(PetscLogCpuToGpu(m * sizeof(PetscInt)));
2346: }
2348: IS colperm = ((Mat_SeqAIJ *)B->data)->col;
2349: PetscBool col_identity;
2350: PetscCall(ISIdentity(colperm, &col_identity));
2351: if (!col_identity) {
2352: const PetscInt *ip;
2354: PetscCall(ISGetIndices(colperm, &ip));
2355: factors->colperm = PetscIntKokkosView(NoInit("colperm"), n);
2356: PetscCallCXX(Kokkos::deep_copy(factors->colperm, PetscIntKokkosViewHost(const_cast<PetscInt *>(ip), n)));
2357: PetscCall(ISRestoreIndices(colperm, &ip));
2358: PetscCall(PetscLogCpuToGpu(n * sizeof(PetscInt)));
2359: }
2361: /* Create sptrsv handles for L, U and their transpose */
2362: #if defined(KOKKOSKERNELS_ENABLE_TPL_CUSPARSE)
2363: auto sptrsv_alg = SPTRSVAlgorithm::SPTRSV_CUSPARSE;
2364: #else
2365: auto sptrsv_alg = SPTRSVAlgorithm::SEQLVLSCHD_TP1;
2366: #endif
2367: factors->khL.create_sptrsv_handle(sptrsv_alg, m, true /* L is lower tri */);
2368: factors->khU.create_sptrsv_handle(sptrsv_alg, m, false /* U is not lower tri */);
2369: factors->khLt.create_sptrsv_handle(sptrsv_alg, m, false /* L^T is not lower tri */);
2370: factors->khUt.create_sptrsv_handle(sptrsv_alg, m, true /* U^T is lower tri */);
2371: }
2373: // Copy the value
2374: for (PetscInt i = 0; i < m; i++) {
2375: PetscInt llen = Bi[i + 1] - Bi[i];
2376: PetscInt ulen = Bdiag[i] - Bdiag[i + 1];
2377: const PetscInt *Li = factors->iL_h.data();
2378: const PetscInt *Ui = factors->iU_h.data();
2380: PetscScalar *La = factors->aL_h.data();
2381: PetscScalar *Ua = factors->aU_h.data();
2383: PetscCall(PetscArraycpy(La + Li[i], Ba + Bi[i], llen)); // entries of L
2384: La[Li[i] + llen] = 1.0; // diagonal entry
2386: Ua[Ui[i]] = 1.0 / Ba[Bdiag[i]]; // diagonal entry
2387: PetscCall(PetscArraycpy(Ua + Ui[i] + 1, Ba + Bdiag[i + 1] + 1, ulen - 1)); // entries of U
2388: }
2390: PetscCallCXX(Kokkos::deep_copy(factors->aL_d, factors->aL_h));
2391: PetscCallCXX(Kokkos::deep_copy(factors->aU_d, factors->aU_h));
2392: // Once the factors' values have changed, we need to update their transpose and redo sptrsv symbolic
2393: factors->transpose_updated = PETSC_FALSE;
2394: factors->sptrsv_symbolic_completed = PETSC_FALSE;
2396: B->ops->solve = MatSolve_SeqAIJKokkos_LU;
2397: B->ops->solvetranspose = MatSolveTranspose_SeqAIJKokkos_LU;
2398: }
2400: B->ops->matsolve = NULL;
2401: B->ops->matsolvetranspose = NULL;
2402: PetscFunctionReturn(PETSC_SUCCESS);
2403: }
2405: static PetscErrorCode MatILUFactorNumeric_SeqAIJKokkos_ILU0(Mat B, Mat A, const MatFactorInfo *info)
2406: {
2407: Mat_SeqAIJKokkos *aijkok = (Mat_SeqAIJKokkos *)A->spptr;
2408: Mat_SeqAIJKokkosTriFactors *factors = (Mat_SeqAIJKokkosTriFactors *)B->spptr;
2409: PetscInt fill_lev = info->levels;
2411: PetscFunctionBegin;
2412: PetscCall(PetscLogGpuTimeBegin());
2413: PetscCheck(!info->factoronhost, PetscObjectComm((PetscObject)A), PETSC_ERR_PLIB, "MatFactorInfo.factoronhost should be false");
2414: PetscCall(MatSeqAIJKokkosSyncDevice(A));
2416: auto a_d = aijkok->a_dual.view_device();
2417: auto i_d = aijkok->i_dual.view_device();
2418: auto j_d = aijkok->j_dual.view_device();
2420: 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));
2422: B->assembled = PETSC_TRUE;
2423: B->preallocated = PETSC_TRUE;
2424: B->ops->solve = MatSolve_SeqAIJKokkos_LU;
2425: B->ops->solvetranspose = MatSolveTranspose_SeqAIJKokkos_LU;
2426: B->ops->matsolve = NULL;
2427: B->ops->matsolvetranspose = NULL;
2429: /* Once the factors' value changed, we need to update their transpose and sptrsv handle */
2430: factors->transpose_updated = PETSC_FALSE;
2431: factors->sptrsv_symbolic_completed = PETSC_FALSE;
2432: /* TODO: log flops, but how to know that? */
2433: PetscCall(PetscLogGpuTimeEnd());
2434: PetscFunctionReturn(PETSC_SUCCESS);
2435: }
2437: // Use KK's spiluk_symbolic() to do ILU0 symbolic factorization, with no row/col reordering
2438: static PetscErrorCode MatILUFactorSymbolic_SeqAIJKokkos_ILU0(Mat B, Mat A, IS, IS, const MatFactorInfo *info)
2439: {
2440: Mat_SeqAIJKokkos *aijkok;
2441: Mat_SeqAIJ *b;
2442: Mat_SeqAIJKokkosTriFactors *factors = (Mat_SeqAIJKokkosTriFactors *)B->spptr;
2443: PetscInt fill_lev = info->levels;
2444: PetscInt nnzA = ((Mat_SeqAIJ *)A->data)->nz, nnzL, nnzU;
2445: PetscInt n = A->rmap->n;
2447: PetscFunctionBegin;
2448: PetscCheck(!info->factoronhost, PetscObjectComm((PetscObject)A), PETSC_ERR_PLIB, "MatFactorInfo's factoronhost should be false as we are doing it on device right now");
2449: PetscCall(MatSeqAIJKokkosSyncDevice(A));
2451: /* Create a spiluk handle and then do symbolic factorization */
2452: nnzL = nnzU = PetscRealIntMultTruncate(info->fill, nnzA);
2453: factors->kh.create_spiluk_handle(SPILUKAlgorithm::SEQLVLSCHD_TP1, n, nnzL, nnzU);
2455: auto spiluk_handle = factors->kh.get_spiluk_handle();
2457: Kokkos::realloc(factors->iL_d, n + 1); /* Free old arrays and realloc */
2458: Kokkos::realloc(factors->jL_d, spiluk_handle->get_nnzL());
2459: Kokkos::realloc(factors->iU_d, n + 1);
2460: Kokkos::realloc(factors->jU_d, spiluk_handle->get_nnzU());
2462: aijkok = (Mat_SeqAIJKokkos *)A->spptr;
2463: auto i_d = aijkok->i_dual.view_device();
2464: auto j_d = aijkok->j_dual.view_device();
2465: PetscCallCXX(spiluk_symbolic(&factors->kh, fill_lev, i_d, j_d, factors->iL_d, factors->jL_d, factors->iU_d, factors->jU_d));
2466: /* TODO: if spiluk_symbolic is asynchronous, do we need to sync before calling get_nnzL()? */
2468: Kokkos::resize(factors->jL_d, spiluk_handle->get_nnzL()); /* Shrink or expand, and retain old value */
2469: Kokkos::resize(factors->jU_d, spiluk_handle->get_nnzU());
2470: Kokkos::realloc(factors->aL_d, spiluk_handle->get_nnzL()); /* No need to retain old value */
2471: Kokkos::realloc(factors->aU_d, spiluk_handle->get_nnzU());
2473: /* TODO: add options to select sptrsv algorithms */
2474: /* Create sptrsv handles for L, U and their transpose */
2475: #if defined(KOKKOSKERNELS_ENABLE_TPL_CUSPARSE)
2476: auto sptrsv_alg = SPTRSVAlgorithm::SPTRSV_CUSPARSE;
2477: #else
2478: auto sptrsv_alg = SPTRSVAlgorithm::SEQLVLSCHD_TP1;
2479: #endif
2481: factors->khL.create_sptrsv_handle(sptrsv_alg, n, true /* L is lower tri */);
2482: factors->khU.create_sptrsv_handle(sptrsv_alg, n, false /* U is not lower tri */);
2483: factors->khLt.create_sptrsv_handle(sptrsv_alg, n, false /* L^T is not lower tri */);
2484: factors->khUt.create_sptrsv_handle(sptrsv_alg, n, true /* U^T is lower tri */);
2486: /* Fill fields of the factor matrix B */
2487: PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(B, MAT_SKIP_ALLOCATION, NULL));
2488: b = (Mat_SeqAIJ *)B->data;
2489: b->nz = b->maxnz = spiluk_handle->get_nnzL() + spiluk_handle->get_nnzU();
2490: B->info.fill_ratio_given = info->fill;
2491: B->info.fill_ratio_needed = nnzA > 0 ? ((PetscReal)b->nz) / ((PetscReal)nnzA) : 1.0;
2493: B->ops->lufactornumeric = MatILUFactorNumeric_SeqAIJKokkos_ILU0;
2494: PetscFunctionReturn(PETSC_SUCCESS);
2495: }
2497: static PetscErrorCode MatLUFactorSymbolic_SeqAIJKokkos(Mat B, Mat A, IS isrow, IS iscol, const MatFactorInfo *info)
2498: {
2499: PetscFunctionBegin;
2500: PetscCall(MatLUFactorSymbolic_SeqAIJ(B, A, isrow, iscol, info));
2501: PetscCheck(!B->spptr, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Expected a NULL spptr");
2502: PetscCallCXX(B->spptr = new Mat_SeqAIJKokkosTriFactors(B->rmap->n));
2503: B->ops->lufactornumeric = MatLUFactorNumeric_SeqAIJKokkos;
2504: PetscFunctionReturn(PETSC_SUCCESS);
2505: }
2507: static PetscErrorCode MatILUFactorSymbolic_SeqAIJKokkos(Mat B, Mat A, IS isrow, IS iscol, const MatFactorInfo *info)
2508: {
2509: PetscBool row_identity = PETSC_FALSE, col_identity = PETSC_FALSE;
2511: PetscFunctionBegin;
2512: if (!info->factoronhost) {
2513: PetscCall(ISIdentity(isrow, &row_identity));
2514: PetscCall(ISIdentity(iscol, &col_identity));
2515: }
2517: PetscCheck(!B->spptr, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Expected a NULL spptr");
2518: PetscCallCXX(B->spptr = new Mat_SeqAIJKokkosTriFactors(B->rmap->n));
2520: if (!info->factoronhost && !info->levels && row_identity && col_identity) { // if level 0 and no reordering
2521: PetscCall(MatILUFactorSymbolic_SeqAIJKokkos_ILU0(B, A, isrow, iscol, info));
2522: } else {
2523: PetscCall(MatILUFactorSymbolic_SeqAIJ(B, A, isrow, iscol, info)); // otherwise, use PETSc's ILU on host
2524: B->ops->lufactornumeric = MatLUFactorNumeric_SeqAIJKokkos;
2525: }
2526: PetscFunctionReturn(PETSC_SUCCESS);
2527: }
2529: static PetscErrorCode MatCholeskyFactorNumeric_SeqAIJKokkos(Mat B, Mat A, const MatFactorInfo *info)
2530: {
2531: PetscFunctionBegin;
2532: PetscCall(MatSeqAIJKokkosSyncHost(A));
2533: PetscCall(MatCholeskyFactorNumeric_SeqAIJ(B, A, info));
2535: if (!info->solveonhost) { // if solve on host, then we don't need to copy L, U to device
2536: Mat_SeqAIJKokkosTriFactors *factors = (Mat_SeqAIJKokkosTriFactors *)B->spptr;
2537: Mat_SeqAIJ *b = static_cast<Mat_SeqAIJ *>(B->data);
2538: const PetscInt *Bi = b->i, *Bj = b->j, *Bdiag = b->diag;
2539: const MatScalar *Ba = b->a;
2540: PetscInt m = B->rmap->n;
2542: if (factors->iU_h.extent(0) == 0) { // First time of numeric factorization
2543: // Allocate memory and copy the structure
2544: factors->iU_h = PetscIntKokkosViewHost(const_cast<PetscInt *>(Bi), m + 1); // wrap Bi as iU_h
2545: factors->jU_h = MatColIdxKokkosViewHost(NoInit("jU_h"), Bi[m]);
2546: factors->aU_h = MatScalarKokkosViewHost(NoInit("aU_h"), Bi[m]);
2547: factors->D_h = MatScalarKokkosViewHost(NoInit("D_h"), m);
2548: factors->aU_d = Kokkos::create_mirror_view(DefaultMemorySpace(), factors->aU_h);
2549: factors->D_d = Kokkos::create_mirror_view(DefaultMemorySpace(), factors->D_h);
2551: // Build jU_h from the skewed Aj
2552: PetscInt *Uj = factors->jU_h.data();
2553: for (PetscInt i = 0; i < m; i++) {
2554: PetscInt ulen = Bi[i + 1] - Bi[i];
2555: Uj[Bi[i]] = i; // diagonal entry
2556: PetscCall(PetscArraycpy(Uj + Bi[i] + 1, Bj + Bi[i], ulen - 1)); // entries of U on the right of the diagonal
2557: }
2559: // Copy iU, jU to device
2560: PetscCallCXX(factors->iU_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), factors->iU_h));
2561: PetscCallCXX(factors->jU_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), factors->jU_h));
2563: // Copy row/col permutation to device
2564: IS rowperm = ((Mat_SeqAIJ *)B->data)->row;
2565: PetscBool row_identity;
2566: PetscCall(ISIdentity(rowperm, &row_identity));
2567: if (!row_identity) {
2568: const PetscInt *ip;
2570: PetscCall(ISGetIndices(rowperm, &ip));
2571: PetscCallCXX(factors->rowperm = PetscIntKokkosView(NoInit("rowperm"), m));
2572: PetscCallCXX(Kokkos::deep_copy(factors->rowperm, PetscIntKokkosViewHost(const_cast<PetscInt *>(ip), m)));
2573: PetscCall(ISRestoreIndices(rowperm, &ip));
2574: PetscCall(PetscLogCpuToGpu(m * sizeof(PetscInt)));
2575: }
2577: // Create sptrsv handles for U and U^T
2578: #if defined(KOKKOSKERNELS_ENABLE_TPL_CUSPARSE)
2579: auto sptrsv_alg = SPTRSVAlgorithm::SPTRSV_CUSPARSE;
2580: #else
2581: auto sptrsv_alg = SPTRSVAlgorithm::SEQLVLSCHD_TP1;
2582: #endif
2583: factors->khU.create_sptrsv_handle(sptrsv_alg, m, false /* U is not lower tri */);
2584: factors->khUt.create_sptrsv_handle(sptrsv_alg, m, true /* U^T is lower tri */);
2585: }
2586: // These pointers were set MatCholeskyFactorNumeric_SeqAIJ(), so we always need to update them
2587: B->ops->solve = MatSolve_SeqAIJKokkos_Cholesky;
2588: B->ops->solvetranspose = MatSolve_SeqAIJKokkos_Cholesky;
2590: // Copy the value
2591: PetscScalar *Ua = factors->aU_h.data();
2592: PetscScalar *D = factors->D_h.data();
2593: for (PetscInt i = 0; i < m; i++) {
2594: D[i] = Ba[Bdiag[i]]; // actually Aa[Adiag[i]] is the inverse of the diagonal
2595: Ua[Bi[i]] = (PetscScalar)1.0; // set the unit diagonal for U
2596: for (PetscInt k = 0; k < Bi[i + 1] - Bi[i] - 1; k++) Ua[Bi[i] + 1 + k] = -Ba[Bi[i] + k];
2597: }
2598: PetscCallCXX(Kokkos::deep_copy(factors->aU_d, factors->aU_h));
2599: PetscCallCXX(Kokkos::deep_copy(factors->D_d, factors->D_h));
2601: factors->sptrsv_symbolic_completed = PETSC_FALSE; // When numeric value changed, we must do these again
2602: factors->transpose_updated = PETSC_FALSE;
2603: }
2605: B->ops->matsolve = NULL;
2606: B->ops->matsolvetranspose = NULL;
2607: PetscFunctionReturn(PETSC_SUCCESS);
2608: }
2610: static PetscErrorCode MatICCFactorSymbolic_SeqAIJKokkos(Mat B, Mat A, IS perm, const MatFactorInfo *info)
2611: {
2612: PetscFunctionBegin;
2613: if (info->solveonhost) {
2614: // If solve on host, we have to change the type, as eventually we need to call MatSolve_SeqSBAIJ_1_NaturalOrdering() etc.
2615: PetscCall(MatSetType(B, MATSEQSBAIJ));
2616: PetscCall(MatSeqSBAIJSetPreallocation(B, 1, MAT_SKIP_ALLOCATION, NULL));
2617: }
2619: PetscCall(MatICCFactorSymbolic_SeqAIJ(B, A, perm, info));
2621: if (!info->solveonhost) {
2622: // If solve on device, B is still a MATSEQAIJKOKKOS, so we are good to allocate B->spptr
2623: PetscCheck(!B->spptr, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Expected a NULL spptr");
2624: PetscCallCXX(B->spptr = new Mat_SeqAIJKokkosTriFactors(B->rmap->n));
2625: B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqAIJKokkos;
2626: }
2627: PetscFunctionReturn(PETSC_SUCCESS);
2628: }
2630: static PetscErrorCode MatCholeskyFactorSymbolic_SeqAIJKokkos(Mat B, Mat A, IS perm, const MatFactorInfo *info)
2631: {
2632: PetscFunctionBegin;
2633: if (info->solveonhost) {
2634: // If solve on host, we have to change the type, as eventually we need to call MatSolve_SeqSBAIJ_1_NaturalOrdering() etc.
2635: PetscCall(MatSetType(B, MATSEQSBAIJ));
2636: PetscCall(MatSeqSBAIJSetPreallocation(B, 1, MAT_SKIP_ALLOCATION, NULL));
2637: }
2639: PetscCall(MatCholeskyFactorSymbolic_SeqAIJ(B, A, perm, info)); // it sets B's two ISes ((Mat_SeqAIJ*)B->data)->{row, col} to perm
2641: if (!info->solveonhost) {
2642: // If solve on device, B is still a MATSEQAIJKOKKOS, so we are good to allocate B->spptr
2643: PetscCheck(!B->spptr, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Expected a NULL spptr");
2644: PetscCallCXX(B->spptr = new Mat_SeqAIJKokkosTriFactors(B->rmap->n));
2645: B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqAIJKokkos;
2646: }
2647: PetscFunctionReturn(PETSC_SUCCESS);
2648: }
2650: // The _Kokkos suffix means we will use Kokkos as a solver for the SeqAIJKokkos matrix
2651: static PetscErrorCode MatFactorGetSolverType_SeqAIJKokkos_Kokkos(Mat A, MatSolverType *type)
2652: {
2653: PetscFunctionBegin;
2654: *type = MATSOLVERKOKKOS;
2655: PetscFunctionReturn(PETSC_SUCCESS);
2656: }
2658: /*MC
2659: MATSOLVERKOKKOS = "Kokkos" - A matrix solver type providing triangular solvers for sequential matrices
2660: on a single GPU of type, `MATSEQAIJKOKKOS`, `MATAIJKOKKOS`.
2662: Level: beginner
2664: .seealso: [](ch_matrices), `Mat`, `PCFactorSetMatSolverType()`, `MatSolverType`, `MatCreateSeqAIJKokkos()`, `MATAIJKOKKOS`
2665: M*/
2666: PETSC_EXTERN PetscErrorCode MatGetFactor_SeqAIJKokkos_Kokkos(Mat A, MatFactorType ftype, Mat *B) /* MatGetFactor_<MatType>_<MatSolverType> */
2667: {
2668: PetscInt n = A->rmap->n;
2669: MPI_Comm comm;
2671: PetscFunctionBegin;
2672: PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
2673: PetscCall(MatCreate(comm, B));
2674: PetscCall(MatSetSizes(*B, n, n, n, n));
2675: PetscCall(MatSetBlockSizesFromMats(*B, A, A));
2676: (*B)->factortype = ftype;
2677: PetscCall(MatSetType(*B, MATSEQAIJKOKKOS));
2678: PetscCall(MatSeqAIJSetPreallocation(*B, MAT_SKIP_ALLOCATION, NULL));
2679: PetscCheck(!(*B)->spptr, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Expected a NULL spptr");
2681: if (ftype == MAT_FACTOR_LU || ftype == MAT_FACTOR_ILU || ftype == MAT_FACTOR_ILUDT) {
2682: (*B)->ops->lufactorsymbolic = MatLUFactorSymbolic_SeqAIJKokkos;
2683: (*B)->ops->ilufactorsymbolic = MatILUFactorSymbolic_SeqAIJKokkos;
2684: PetscCall(PetscStrallocpy(MATORDERINGND, (char **)&(*B)->preferredordering[MAT_FACTOR_LU]));
2685: PetscCall(PetscStrallocpy(MATORDERINGNATURAL, (char **)&(*B)->preferredordering[MAT_FACTOR_ILU]));
2686: PetscCall(PetscStrallocpy(MATORDERINGNATURAL, (char **)&(*B)->preferredordering[MAT_FACTOR_ILUDT]));
2687: } else if (ftype == MAT_FACTOR_CHOLESKY || ftype == MAT_FACTOR_ICC) {
2688: (*B)->ops->iccfactorsymbolic = MatICCFactorSymbolic_SeqAIJKokkos;
2689: (*B)->ops->choleskyfactorsymbolic = MatCholeskyFactorSymbolic_SeqAIJKokkos;
2690: PetscCall(PetscStrallocpy(MATORDERINGND, (char **)&(*B)->preferredordering[MAT_FACTOR_CHOLESKY]));
2691: PetscCall(PetscStrallocpy(MATORDERINGNATURAL, (char **)&(*B)->preferredordering[MAT_FACTOR_ICC]));
2692: } else SETERRQ(comm, PETSC_ERR_SUP, "MatFactorType %s is not supported by MatType SeqAIJKokkos", MatFactorTypes[ftype]);
2694: // The factorization can use the ordering provided in MatLUFactorSymbolic(), MatCholeskyFactorSymbolic() etc, though we do it on host
2695: (*B)->canuseordering = PETSC_TRUE;
2696: PetscCall(PetscObjectComposeFunction((PetscObject)*B, "MatFactorGetSolverType_C", MatFactorGetSolverType_SeqAIJKokkos_Kokkos));
2697: PetscFunctionReturn(PETSC_SUCCESS);
2698: }
2700: PETSC_INTERN PetscErrorCode MatSolverTypeRegister_Kokkos(void)
2701: {
2702: PetscFunctionBegin;
2703: PetscCall(MatSolverTypeRegister(MATSOLVERKOKKOS, MATSEQAIJKOKKOS, MAT_FACTOR_LU, MatGetFactor_SeqAIJKokkos_Kokkos));
2704: PetscCall(MatSolverTypeRegister(MATSOLVERKOKKOS, MATSEQAIJKOKKOS, MAT_FACTOR_CHOLESKY, MatGetFactor_SeqAIJKokkos_Kokkos));
2705: PetscCall(MatSolverTypeRegister(MATSOLVERKOKKOS, MATSEQAIJKOKKOS, MAT_FACTOR_ILU, MatGetFactor_SeqAIJKokkos_Kokkos));
2706: PetscCall(MatSolverTypeRegister(MATSOLVERKOKKOS, MATSEQAIJKOKKOS, MAT_FACTOR_ICC, MatGetFactor_SeqAIJKokkos_Kokkos));
2707: PetscFunctionReturn(PETSC_SUCCESS);
2708: }
2710: /* Utility to print out a KokkosCsrMatrix for debugging */
2711: PETSC_INTERN PetscErrorCode PrintCsrMatrix(const KokkosCsrMatrix &csrmat)
2712: {
2713: const auto &iv = Kokkos::create_mirror_view_and_copy(HostMirrorMemorySpace(), csrmat.graph.row_map);
2714: const auto &jv = Kokkos::create_mirror_view_and_copy(HostMirrorMemorySpace(), csrmat.graph.entries);
2715: const auto &av = Kokkos::create_mirror_view_and_copy(HostMirrorMemorySpace(), csrmat.values);
2716: const PetscInt *i = iv.data();
2717: const PetscInt *j = jv.data();
2718: const PetscScalar *a = av.data();
2719: PetscInt m = csrmat.numRows(), n = csrmat.numCols(), nnz = csrmat.nnz();
2721: PetscFunctionBegin;
2722: PetscCall(PetscPrintf(PETSC_COMM_SELF, "%" PetscInt_FMT " x %" PetscInt_FMT " SeqAIJKokkos, with %" PetscInt_FMT " nonzeros\n", m, n, nnz));
2723: for (PetscInt k = 0; k < m; k++) {
2724: PetscCall(PetscPrintf(PETSC_COMM_SELF, "%" PetscInt_FMT ": ", k));
2725: for (PetscInt p = i[k]; p < i[k + 1]; p++) PetscCall(PetscPrintf(PETSC_COMM_SELF, "%" PetscInt_FMT "(%.1f), ", j[p], (double)PetscRealPart(a[p])));
2726: PetscCall(PetscPrintf(PETSC_COMM_SELF, "\n"));
2727: }
2728: PetscFunctionReturn(PETSC_SUCCESS);
2729: }