Actual source code: mpiaijkok.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/sfimpl.h>
  6: #include <petsc/private/kokkosimpl.hpp>
  7: #include <../src/mat/impls/aij/seq/kokkos/aijkok.hpp>
  8: #include <../src/mat/impls/aij/mpi/mpiaij.h>
  9: #include <KokkosSparse_spadd.hpp>
 10: #include <KokkosSparse_spgemm.hpp>

 12: static PetscErrorCode MatAssemblyEnd_MPIAIJKokkos(Mat A, MatAssemblyType mode)
 13: {
 14:   Mat_MPIAIJ *mpiaij = (Mat_MPIAIJ *)A->data;

 16:   PetscFunctionBegin;
 17:   PetscCall(MatAssemblyEnd_MPIAIJ(A, mode));
 18:   /* E.g., MatCreateSubMatrix() calls MatCreateMPIAIJWithSeqAIJ(comm,A,B,..), which creates Bnew of SEQAIJ and destroys B of SEQAIJKOKKOS.
 19:      Thus we finalize A/B/lvec's type in MatAssemblyEnd() to handle various cases.
 20:    */
 21:   if (mode == MAT_FINAL_ASSEMBLY) {
 22:     PetscScalarKokkosView v;

 24:     PetscCall(MatSetType(mpiaij->A, MATSEQAIJKOKKOS));
 25:     PetscCall(MatSetType(mpiaij->B, MATSEQAIJKOKKOS));
 26:     PetscCall(VecSetType(mpiaij->lvec, VECSEQKOKKOS));  // lvec is init'ed on host, without copying to device
 27:     PetscCall(VecGetKokkosViewWrite(mpiaij->lvec, &v)); // mark lvec updated on device, as we never need to init lvec on device
 28:     PetscCall(VecRestoreKokkosViewWrite(mpiaij->lvec, &v));
 29:   }
 30:   PetscFunctionReturn(PETSC_SUCCESS);
 31: }

 33: static PetscErrorCode MatMPIAIJSetPreallocation_MPIAIJKokkos(Mat mat, PetscInt d_nz, const PetscInt d_nnz[], PetscInt o_nz, const PetscInt o_nnz[])
 34: {
 35:   Mat_MPIAIJ *mpiaij;

 37:   PetscFunctionBegin;
 38:   // reuse MPIAIJ's preallocation, which sets A/B's blocksize along other things
 39:   PetscCall(MatMPIAIJSetPreallocation_MPIAIJ(mat, d_nz, d_nnz, o_nz, o_nnz));
 40:   mpiaij = static_cast<Mat_MPIAIJ *>(mat->data);
 41:   PetscCall(MatConvert_SeqAIJ_SeqAIJKokkos(mpiaij->A, MATSEQAIJKOKKOS, MAT_INPLACE_MATRIX, &mpiaij->A));
 42:   PetscCall(MatConvert_SeqAIJ_SeqAIJKokkos(mpiaij->B, MATSEQAIJKOKKOS, MAT_INPLACE_MATRIX, &mpiaij->B));
 43:   PetscFunctionReturn(PETSC_SUCCESS);
 44: }

 46: static PetscErrorCode MatMult_MPIAIJKokkos(Mat mat, Vec xx, Vec yy)
 47: {
 48:   Mat_MPIAIJ *mpiaij = (Mat_MPIAIJ *)mat->data;
 49:   PetscInt    nt;

 51:   PetscFunctionBegin;
 52:   PetscCall(VecGetLocalSize(xx, &nt));
 53:   PetscCheck(nt == mat->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Incompatible partition of mat (%" PetscInt_FMT ") and xx (%" PetscInt_FMT ")", mat->cmap->n, nt);
 54:   PetscCall(VecScatterBegin(mpiaij->Mvctx, xx, mpiaij->lvec, INSERT_VALUES, SCATTER_FORWARD));
 55:   PetscUseTypeMethod(mpiaij->A, mult, xx, yy);
 56:   PetscCall(VecScatterEnd(mpiaij->Mvctx, xx, mpiaij->lvec, INSERT_VALUES, SCATTER_FORWARD));
 57:   PetscUseTypeMethod(mpiaij->B, multadd, mpiaij->lvec, yy, yy);
 58:   PetscFunctionReturn(PETSC_SUCCESS);
 59: }

 61: static PetscErrorCode MatMultAdd_MPIAIJKokkos(Mat mat, Vec xx, Vec yy, Vec zz)
 62: {
 63:   Mat_MPIAIJ *mpiaij = (Mat_MPIAIJ *)mat->data;
 64:   PetscInt    nt;

 66:   PetscFunctionBegin;
 67:   PetscCall(VecGetLocalSize(xx, &nt));
 68:   PetscCheck(nt == mat->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Incompatible partition of mat (%" PetscInt_FMT ") and xx (%" PetscInt_FMT ")", mat->cmap->n, nt);
 69:   PetscCall(VecScatterBegin(mpiaij->Mvctx, xx, mpiaij->lvec, INSERT_VALUES, SCATTER_FORWARD));
 70:   PetscUseTypeMethod(mpiaij->A, multadd, xx, yy, zz);
 71:   PetscCall(VecScatterEnd(mpiaij->Mvctx, xx, mpiaij->lvec, INSERT_VALUES, SCATTER_FORWARD));
 72:   PetscUseTypeMethod(mpiaij->B, multadd, mpiaij->lvec, zz, zz);
 73:   PetscFunctionReturn(PETSC_SUCCESS);
 74: }

 76: static PetscErrorCode MatMultTranspose_MPIAIJKokkos(Mat mat, Vec xx, Vec yy)
 77: {
 78:   Mat_MPIAIJ *mpiaij = (Mat_MPIAIJ *)mat->data;
 79:   PetscInt    nt;

 81:   PetscFunctionBegin;
 82:   PetscCall(VecGetLocalSize(xx, &nt));
 83:   PetscCheck(nt == mat->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Incompatible partition of mat (%" PetscInt_FMT ") and xx (%" PetscInt_FMT ")", mat->rmap->n, nt);
 84:   PetscUseTypeMethod(mpiaij->B, multtranspose, xx, mpiaij->lvec);
 85:   PetscUseTypeMethod(mpiaij->A, multtranspose, xx, yy);
 86:   PetscCall(VecScatterBegin(mpiaij->Mvctx, mpiaij->lvec, yy, ADD_VALUES, SCATTER_REVERSE));
 87:   PetscCall(VecScatterEnd(mpiaij->Mvctx, mpiaij->lvec, yy, ADD_VALUES, SCATTER_REVERSE));
 88:   PetscFunctionReturn(PETSC_SUCCESS);
 89: }

 91: /* Merge the "A, B" matrices of mat into a matrix C.  mat's type is MPIAIJKOKKOS. C's type is MATSEQAIJKOKKOS.
 92:    A is put before B. C's size would be A->rmap->n by (A->cmap->n + B->cmap->n).
 93:    C still uses local column ids. Their corresponding global column ids are returned in glob.
 94: */
 95: static PetscErrorCode MatMPIAIJGetLocalMatMerge_MPIAIJKokkos(Mat mat, MatReuse reuse, IS *glob, Mat *C)
 96: {
 97:   Mat             Ad, Ao;
 98:   const PetscInt *cmap;

100:   PetscFunctionBegin;
101:   PetscCall(MatMPIAIJGetSeqAIJ(mat, &Ad, &Ao, &cmap));
102:   PetscCall(MatSeqAIJKokkosMergeMats(Ad, Ao, reuse, C));
103:   if (glob) {
104:     PetscInt cst, i, dn, on, *gidx;
105:     PetscCall(MatGetLocalSize(Ad, NULL, &dn));
106:     PetscCall(MatGetLocalSize(Ao, NULL, &on));
107:     PetscCall(MatGetOwnershipRangeColumn(mat, &cst, NULL));
108:     PetscCall(PetscMalloc1(dn + on, &gidx));
109:     for (i = 0; i < dn; i++) gidx[i] = cst + i;
110:     for (i = 0; i < on; i++) gidx[i + dn] = cmap[i];
111:     PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)Ad), dn + on, gidx, PETSC_OWN_POINTER, glob));
112:   }
113:   PetscFunctionReturn(PETSC_SUCCESS);
114: }

116: /* Structs used in matrix products of type C=AB, C=A^tB and C=B^tAB */
117: struct MatMatStruct {
118:   PetscInt            n, *garray;     // C's garray and its size.
119:   KokkosCsrMatrix     Cd, Co;         // C is in split form matrices (all in local column indcies)
120:   KokkosCsrMatrix     C1, C2, C3, C4; // intermediate mat products
121:   KokkosCsrMatrix     C2_mid, C4_mid; // alias of C2, C4; share their a[], i[], but with different j[] (hence column size)
122:   PetscIntKokkosView  E_NzLeft;
123:   PetscSF             sf = nullptr; // SF to bcast or reduce matrices E to F
124:   MatScalarKokkosView rootBuf, leafBuf;
125:   KokkosCsrMatrix     Fd, Fo; // F in split form

127:   KernelHandle kh1; // compute C1, add C1+C3 or C1+Fd
128:   KernelHandle kh2; // compute C2, add C2+C4 or C2+Fo
129:   KernelHandle kh3; // compute C3
130:   KernelHandle kh4; // compute C4

132:   PetscInt E_TeamSize; // kernel launching parameters in merging E or splitting F
133:   PetscInt E_VectorLength;
134:   PetscInt E_RowsPerTeam;
135:   PetscInt F_TeamSize;
136:   PetscInt F_VectorLength;
137:   PetscInt F_RowsPerTeam;

139:   ~MatMatStruct()
140:   {
141:     PetscFunctionBegin;
142:     PetscCallAbort(PETSC_COMM_SELF, PetscSFDestroy(&sf));
143:     PetscFunctionReturnVoid();
144:   }
145: };

147: struct MatMatStruct_AB : public MatMatStruct {
148:   PetscIntKokkosView F_NzLeft; // plans to split F (in leafbuf) into Fd, Fo
149:   PetscIntKokkosView irootloc; // plans to put E (i.e., Bd, Bo) into rootBuf
150:   PetscIntKokkosView rowoffset;
151: };

153: struct MatMatStruct_AtB : public MatMatStruct {
154:   MatColIdxKokkosView Fdjmap; // plans to reduce data in rootBuf to Fd, Fo
155:   MatColIdxKokkosView Fdjperm;
156:   MatColIdxKokkosView Fojmap;
157:   MatColIdxKokkosView Fojperm;
158: };

160: struct MatProductCtx_MPIAIJKokkos {
161:   MatMatStruct_AB  *mmAB     = nullptr;
162:   MatMatStruct_AtB *mmAtB    = nullptr;
163:   PetscBool         reusesym = PETSC_FALSE;
164:   Mat               Z        = nullptr; // store Z=AB in computing BtAB

166:   ~MatProductCtx_MPIAIJKokkos()
167:   {
168:     delete mmAB;
169:     delete mmAtB;
170:     PetscCallAbort(PETSC_COMM_SELF, MatDestroy(&Z));
171:   }
172: };

174: static PetscErrorCode MatProductCtxDestroy_MPIAIJKokkos(PetscCtxRt data)
175: {
176:   PetscFunctionBegin;
177:   PetscCallCXX(delete *reinterpret_cast<MatProductCtx_MPIAIJKokkos **>(data));
178:   PetscFunctionReturn(PETSC_SUCCESS);
179: }

181: // Adapted from Kokkos-Kernels spmv_launch_parameters(), to get parameters in Kokkos nested loops which we used to merge or
182: // split csr matrices. The rule is to have "vector_length * team_size" be around 256 on GPUs (e.g., for a CUDA thread block)
183: template <class ExecutionSpace>
184: static PetscErrorCode MatMergeGetLaunchParameters(PetscInt numRows, PetscInt nnz, PetscInt rows_per_thread, PetscInt &team_size, PetscInt &vector_length, PetscInt &rows_per_team)
185: {
186: #if PETSC_PKG_KOKKOS_KERNELS_VERSION_LE(4, 4, 1)
187:   constexpr bool is_gpu_exec_space = KokkosKernels::Impl::kk_is_gpu_exec_space<ExecutionSpace>();
188: #else
189:   constexpr bool is_gpu_exec_space = KokkosKernels::Impl::is_gpu_exec_space_v<ExecutionSpace>;
190: #endif
191:   Kokkos::TeamPolicy<ExecutionSpace> teamPolicy(128, Kokkos::AUTO);

193:   PetscFunctionBegin;
194:   PetscInt nnz_per_row = numRows ? (nnz / numRows) : 0; // we might meet empty matrices

196:   if (nnz_per_row < 1) nnz_per_row = 1;

198:   int max_vector_length = teamPolicy.vector_length_max();

200:   if (vector_length < 1) {
201:     vector_length = 1;
202:     while (vector_length < max_vector_length && vector_length * 6 < nnz_per_row) vector_length *= 2;
203:   }

205:   // Determine rows per thread
206:   if (rows_per_thread < 1) {
207:     if (is_gpu_exec_space) rows_per_thread = 1;
208:     else {
209:       if (nnz_per_row < 20 && nnz > 5000000) {
210:         rows_per_thread = 256;
211:       } else rows_per_thread = 64;
212:     }
213:   }

215:   if (team_size < 1) {
216:     if (is_gpu_exec_space) {
217:       team_size = 256 / vector_length;
218:     } else {
219:       team_size = 1;
220:     }
221:   }

223:   rows_per_team = rows_per_thread * team_size;

225:   if (rows_per_team < 0) {
226:     PetscInt nnz_per_team = 4096;
227:     PetscInt conc         = ExecutionSpace().concurrency();
228:     while ((conc * nnz_per_team * 4 > nnz) && (nnz_per_team > 256)) nnz_per_team /= 2;
229:     rows_per_team = (nnz_per_team + nnz_per_row - 1) / nnz_per_row;
230:   }
231:   PetscFunctionReturn(PETSC_SUCCESS);
232: }

234: /*
235:   Reduce two sets of global indices into local ones

237:   Input Parameters:
238: +  n1          - size of garray1[], the first set
239: .  garray1[n1] - a sorted global index array (without duplicates)
240: .  m           - size of indices[], the second set
241: -  indices[m]  - a unsorted global index array (might have duplicates), which will be updated on output into local ones

243:   Output Parameters:
244: +  n2          - size of garray2[], the merged set, which combines garray1[] and indices[]
245: .  garray2[n2] - allocated by callee using PetscMalloc1(). Contains sorted unique global indices (without duplicates). Caller needs to free it.
246: .  map[n1]     - allocated by caller. It gives garray1[i] = garray2[map[i]]
247: -  indices[m]  - on output, global indices in this array are rewritten with local ones, i.e, indices_input[i] = garray2[indices_output[i]]

249:    Example, say
250:     n1         = 5
251:     garray1[5] = {1, 4, 7, 8, 10}
252:     m          = 4
253:     indices[4] = {2, 4, 8, 9}

255:    Combining them together, we have 7 global indices in garray2[]
256:     n2         = 7
257:     garray2[7] = {1, 2, 4, 7, 8, 9, 10}

259:    And we have map[] to connect "garray1[i] = garray2[map[i]], i=[0,n1)"
260:     map[5] = {0, 2, 3, 4, 6}

262:    On output, indices[] is updated with local indices
263:     indices[4] = {1, 2, 4, 5}
264: */
265: static PetscErrorCode ReduceTwoSetsOfGlobalIndices(PetscInt n1, const PetscInt *garray1, PetscInt m, PetscInt *indices, PetscInt *n2_, PetscInt **garray2_, PetscInt *map)
266: {
267:   PetscHMapI    g2l = nullptr;
268:   PetscHashIter iter;
269:   PetscInt      tot, key, val; // total unique global indices. key is global id; val is local id
270:   PetscInt      n2, *garray2;

272:   PetscFunctionBegin;
273:   tot = 0;
274:   PetscCall(PetscHMapICreateWithSize(n1, &g2l));
275:   for (PetscInt i = 0; i < m; i++) {                                // insert those in indices[]
276:     PetscCall(PetscHMapIGetWithDefault(g2l, indices[i], -1, &val)); // if not exist, val is set with -1
277:     if (val < 0) PetscCall(PetscHMapISet(g2l, indices[i], tot++));  // val < 0 means gid is not in the hash table yet
278:   }

280:   for (PetscInt i = 0; i < n1; i++) { // insert those in garray1[]
281:     PetscCall(PetscHMapIGetWithDefault(g2l, garray1[i], -1, &val));
282:     if (val < 0) PetscCall(PetscHMapISet(g2l, garray1[i], tot++));
283:   }

285:   // Pull out (unique) globals in the hash table and put them in garray2[]
286:   n2 = tot;
287:   PetscCall(PetscMalloc1(n2, &garray2));
288:   tot = 0;
289:   PetscHashIterBegin(g2l, iter);
290:   while (!PetscHashIterAtEnd(g2l, iter)) {
291:     PetscHashIterGetKey(g2l, iter, key);
292:     PetscHashIterNext(g2l, iter);
293:     garray2[tot++] = key;
294:   }

296:   // Sort garray2[] and then map them to local indices starting from 0
297:   PetscCall(PetscSortInt(n2, garray2));
298:   PetscCall(PetscHMapIClear(g2l));
299:   for (PetscInt i = 0; i < tot; i++) PetscCall(PetscHMapISet(g2l, garray2[i], i)); // i is the local id

301:   // Rewrite indices[] with local indices
302:   for (PetscInt i = 0; i < m; i++) {
303:     PetscCall(PetscHMapIGetWithDefault(g2l, indices[i], -1, &val));
304:     PetscAssert(val >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Met a negative local column index");
305:     indices[i] = val;
306:   }
307:   // Record the map that maps garray1[i] to garray2[map[i]]
308:   for (PetscInt i = 0; i < n1; i++) PetscCall(PetscHMapIGetWithDefault(g2l, garray1[i], -1, &map[i]));
309:   PetscCall(PetscHMapIDestroy(&g2l));
310:   *n2_      = n2;
311:   *garray2_ = garray2;
312:   PetscFunctionReturn(PETSC_SUCCESS);
313: }

315: /*
316:   MatMPIAIJKokkosReduce - Reduce rows of a MPIAIJKOKKOS matrix (E, in split form) to produce another matrix (F, also in split form, stored in mm)

318:   It is the reverse of MatMPIAIJKokkosBcast() in some sense, but with a different signature since we do not really need a fully populated MPIAIJKOKKOS E.

320:   Think each row of E as a leaf, then the given ownerSF specifies roots for the leaves. Roots may connect to multiple leaves.
321:   In this routine, we sparse-merge leaves (rows) at their roots to form potentially longer rows in F. F's number of rows will be nroots of ownerSF.

323:   Input Parameters:
324: +  comm       - MPI communicator of E
325: .  A          - diag block of E, using local column indices
326: .  B          - off-diag block of E, using local column indices
327: .  cstart      - (global) start column of Ed
328: .  cend        - (global) end column + 1 of Ed.  In other words, E's column ownership is in range of [cstart, cend)
329: .  garray1[n1] - global column indices of Eo. Here n1 is Eo's column size.
330: .  ownerSF     - the SF specifies ownership (root) of rows in E
331: .  reuse       - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
332: -  mm          - to stash intermediate data structures for reuse

334:   Output Parameters:
335: +  map[n1]  - allocated by caller. It maps garray1[] to garray2[]. See more at ReduceTwoSetsOfGlobalIndices().
336: -  mm       - contains various info, such as garray2[], F (Fd, Fo) etc.

338:   Notes:
339:   When reuse = MAT_REUSE_MATRIX, cstart, cend, garray1, ownerSF, map are not significant.

341:  */
342: static PetscErrorCode MatMPIAIJKokkosReduceBegin(MPI_Comm comm, KokkosCsrMatrix A, KokkosCsrMatrix B, PetscInt cstart, PetscInt cend, const PetscInt *garray1, PetscSF ownerSF, MatReuse reuse, PetscInt *map, MatMatStruct_AtB *mm)
343: {
344:   PetscFunctionBegin;
345:   if (reuse == MAT_INITIAL_MATRIX) {
346:     PetscInt Em = A.numRows(), Fm;
347:     PetscInt n1 = B.numCols();

349:     PetscCall(PetscSFGetGraph(ownerSF, &Fm, NULL, NULL, NULL)); // Fm = #rows of F = nroots of ownerSF

351:     // Do the analysis on host
352:     auto                 Ai_h = Kokkos::create_mirror_view_and_copy(HostMirrorMemorySpace(), A.graph.row_map);
353:     auto                 Aj_h = Kokkos::create_mirror_view_and_copy(HostMirrorMemorySpace(), A.graph.entries);
354:     auto                 Bi_h = Kokkos::create_mirror_view_and_copy(HostMirrorMemorySpace(), B.graph.row_map);
355:     auto                 Bj_h = Kokkos::create_mirror_view_and_copy(HostMirrorMemorySpace(), B.graph.entries);
356:     const MatRowMapType *Ai = Ai_h.data(), *Bi = Bi_h.data();
357:     const MatColIdxType *Aj = Aj_h.data(), *Bj = Bj_h.data();

359:     // Count how many nonzeros of each row in E are in the left of the diag block [cstart,cend)
360:     PetscIntKokkosViewHost E_NzLeft_h(NoInit("E_NzLeft_h"), Em), E_RowLen_h(NoInit("E_RowLen_h"), Em);
361:     PetscInt              *E_NzLeft = E_NzLeft_h.data(), *E_RowLen = E_RowLen_h.data();
362:     for (PetscInt i = 0; i < Em; i++) {
363:       const PetscInt *first, *last, *it;
364:       PetscInt        count, step;
365:       // std::lower_bound(first,last,cstart), but need to use global column indices
366:       first = Bj + Bi[i];
367:       last  = Bj + Bi[i + 1];
368:       count = last - first;
369:       while (count > 0) {
370:         it   = first;
371:         step = count / 2;
372:         it += step;
373:         if (garray1[*it] < cstart) { // map local to global
374:           first = ++it;
375:           count -= step + 1;
376:         } else count = step;
377:       }
378:       E_NzLeft[i] = first - (Bj + Bi[i]);
379:       E_RowLen[i] = (Ai[i + 1] - Ai[i]) + (Bi[i + 1] - Bi[i]);
380:     }

382:     // Get length of rows (i.e., sizes of leaves) that contribute to my roots
383:     const PetscMPIInt *iranks, *ranks;
384:     const PetscInt    *ioffset, *irootloc, *roffset, *rmine;
385:     PetscMPIInt        niranks, nranks;
386:     MPI_Request       *reqs;
387:     PetscMPIInt        tag;
388:     PetscSF            reduceSF;
389:     PetscInt          *sdisp, *rdisp;

391:     PetscCall(PetscCommGetNewTag(comm, &tag));
392:     PetscCall(PetscSFGetLeafRanks(ownerSF, &niranks, &iranks, &ioffset, &irootloc));  // get leaf ranks connecting to roots on this process (I'll recv from them)
393:     PetscCall(PetscSFGetRootRanks(ownerSF, &nranks, &ranks, &roffset, &rmine, NULL)); // get root ranks this process connects (I'll send to them)

395:     // Find out length of each row I will receive. Even for the same row index, when they are from
396:     // different senders, they might have different lengths (and sparsity patterns)
397:     PetscInt  sendRowCnt = roffset[nranks], recvRowCnt = ioffset[niranks];
398:     PetscInt *sendRowLen, *recvRowLen; // lengths of rows of I need to send/recv per process

400:     PetscCall(PetscMalloc5(sendRowCnt, &sendRowLen, recvRowCnt + 1, &recvRowLen, nranks, &sdisp, niranks + 1, &rdisp, nranks + niranks, &reqs));

402:     for (PetscInt i = 0; i < sendRowCnt; i++) sendRowLen[i] = E_RowLen[rmine[i]];
403:     recvRowLen[0] = 0; // since we will make it in CSR format later
404:     recvRowLen++;      // advance the pointer now
405:     for (PetscInt i = 0; i < niranks; i++) PetscCallMPI(MPIU_Irecv(&recvRowLen[ioffset[i]], ioffset[i + 1] - ioffset[i], MPIU_INT, iranks[i], tag, comm, &reqs[nranks + i]));
406:     for (PetscInt i = 0; i < nranks; i++) PetscCallMPI(MPIU_Isend(&sendRowLen[roffset[i]], roffset[i + 1] - roffset[i], MPIU_INT, ranks[i], tag, comm, &reqs[i]));
407:     PetscCallMPI(MPI_Waitall(nranks + niranks, reqs, MPI_STATUSES_IGNORE));

409:     // Build the real PetscSF for reducing E rows (buffer to buffer)
410:     rdisp[0] = 0;
411:     for (PetscInt i = 0; i < niranks; i++) {
412:       rdisp[i + 1] = rdisp[i];
413:       for (PetscInt j = ioffset[i]; j < ioffset[i + 1]; j++) rdisp[i + 1] += recvRowLen[j];
414:     }
415:     recvRowLen--; // put it back into csr format
416:     for (PetscInt i = 0; i < recvRowCnt; i++) recvRowLen[i + 1] += recvRowLen[i];

418:     for (PetscInt i = 0; i < nranks; i++) PetscCallMPI(MPIU_Irecv(&sdisp[i], 1, MPIU_INT, ranks[i], tag, comm, &reqs[i]));
419:     for (PetscInt i = 0; i < niranks; i++) PetscCallMPI(MPIU_Isend(&rdisp[i], 1, MPIU_INT, iranks[i], tag, comm, &reqs[nranks + i]));
420:     PetscCallMPI(MPI_Waitall(nranks + niranks, reqs, MPI_STATUSES_IGNORE));

422:     PetscInt     nleaves = 0, Enz = 0;    // leaves are nonzeros I will send
423:     PetscInt     nroots = rdisp[niranks]; // roots are nonzeros I will recv
424:     PetscSFNode *iremote;

426:     for (PetscInt i = 0; i < Em; i++) Enz += E_RowLen[i];
427:     PetscAssert(A.nnz() + B.nnz() == Enz, comm, PETSC_ERR_PLIB, "Enz should be equal to sum of nnz of A and B");
428:     PetscCallMPI(PetscMalloc1(Enz, &iremote)); // no free, since we give ownership to reduceSF

430:     for (PetscInt i = 0; i < nranks; i++) {
431:       PetscInt count = 0;
432:       for (PetscInt j = roffset[i]; j < roffset[i + 1]; j++) count += E_RowLen[rmine[j]];
433:       for (PetscInt j = 0; j < count; j++) {
434:         iremote[nleaves + j].rank  = ranks[i];
435:         iremote[nleaves + j].index = sdisp[i] + j;
436:       }
437:       nleaves += count;
438:     }
439:     PetscCheck(nleaves == Enz, comm, PETSC_ERR_PLIB, "nleaves should be equal to Enz");

441:     PetscCall(PetscSFCreate(comm, &reduceSF));
442:     PetscCall(PetscSFSetGraph(reduceSF, nroots, nleaves, NULL, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));

444:     // Copy (global) column indices of the needed rows in E to sendCol[], and then PetscSFReduce to recvCol[]
445:     PetscInt *sendCol, *recvCol;
446:     PetscCall(PetscMalloc2(nleaves, &sendCol, nroots, &recvCol));
447:     for (PetscInt k = 0; k < roffset[nranks]; k++) {
448:       PetscInt  i      = rmine[k]; // row to be copied
449:       PetscInt *buf    = &sendCol[Ai[i] + Bi[i]];
450:       PetscInt  nzLeft = E_NzLeft[i];
451:       PetscInt  alen = Ai[i + 1] - Ai[i], blen = Bi[i + 1] - Bi[i];
452:       for (PetscInt j = 0; j < alen + blen; j++) {
453:         if (j < nzLeft) {
454:           buf[j] = garray1[Bj[Bi[i] + j]]; // left B, in global
455:         } else if (j < nzLeft + alen) {
456:           buf[j] = Aj[Ai[i] + j - nzLeft] + cstart; // diag A, also in global
457:         } else {
458:           buf[j] = garray1[Bj[Bi[i] + j - alen]]; // right B, in global
459:         }
460:       }
461:     }
462:     PetscCall(PetscSFReduceWithMemTypeBegin(reduceSF, MPIU_INT, PETSC_MEMTYPE_HOST, sendCol, PETSC_MEMTYPE_HOST, recvCol, MPI_REPLACE));
463:     PetscCall(PetscSFReduceEnd(reduceSF, MPIU_INT, sendCol, recvCol, MPI_REPLACE));

465:     // With recvCol[], we do a series of analysis to get i, j of Fd, Fo, and build plans to reduce nonzeros in recv buffers to Fd and Fo
466:     PetscInt *recvRowPerm, *recvColSorted;
467:     PetscInt *recvNzPerm, *recvNzPermSorted;
468:     PetscCall(PetscMalloc4(recvRowCnt, &recvRowPerm, nroots, &recvColSorted, nroots, &recvNzPerm, nroots, &recvNzPermSorted));

470:     for (PetscInt i = 0; i < nroots; i++) recvNzPerm[i] = i;                   // numbering all received nonzeros
471:     for (PetscInt i = 0; i < recvRowCnt; i++) recvRowPerm[i] = i;              // put up a permutation array, so that after sorting we know where to get a row in recvCol[]
472:     PetscCall(PetscSortIntWithPermutation(recvRowCnt, irootloc, recvRowPerm)); // irootloc[] (owned by ownerSF) won't be changed

474:     // i[] array, nz are always easiest to compute
475:     MatRowMapKokkosViewHost Fdi_h(NoInit("Fdi_h"), Fm + 1), Foi_h(NoInit("Foi_h"), Fm + 1);
476:     MatRowMapType          *Fdi, *Foi;
477:     PetscInt                FnzDups = 0, Fdnz = 0, FdnzDups = 0, Fonz = 0, FonzDups = 0; // nz (with or without dups) in F, Fd, Fo
478:     PetscInt                iter;

480:     Kokkos::deep_copy(Fdi_h, 0); // zero, as we will do 'val++' on them
481:     Kokkos::deep_copy(Foi_h, 0);
482:     Fdi  = Fdi_h.data() + 1; // +1 for easy indexing in code below
483:     Foi  = Foi_h.data() + 1;
484:     iter = 0;
485:     while (iter < recvRowCnt) { // iter over received rows
486:       PetscInt curRowIdx = irootloc[recvRowPerm[iter]];
487:       PetscInt dupRows   = 1; // current row has this many contributing rows (of various sparsity patterns)

489:       while (iter + dupRows < recvRowCnt && irootloc[recvRowPerm[iter + dupRows]] == curRowIdx) dupRows++;

491:       // Copy column indices (and their permutation) of these rows into recvColSorted & recvNzPermSorted
492:       PetscInt  nz    = 0; // nz (with dups) in the current row
493:       PetscInt *jbuf  = recvColSorted + FnzDups;
494:       PetscInt *pbuf  = recvNzPermSorted + FnzDups;
495:       PetscInt *jbuf2 = jbuf; // temp pointers
496:       PetscInt *pbuf2 = pbuf;
497:       for (PetscInt d = 0; d < dupRows; d++) {
498:         PetscInt i   = recvRowPerm[iter + d];
499:         PetscInt len = recvRowLen[i + 1] - recvRowLen[i];
500:         PetscCall(PetscArraycpy(jbuf2, &recvCol[recvRowLen[i]], len));
501:         PetscCall(PetscArraycpy(pbuf2, &recvNzPerm[recvRowLen[i]], len));
502:         jbuf2 += len;
503:         pbuf2 += len;
504:         nz += len;
505:       }
506:       PetscCall(PetscIntSortSemiOrderedWithArray(nz, jbuf, pbuf)); // It could be improved with k-way merge sort, since the rows are already sorted

508:       // Scan column indices (in jbuf[0,nz), might have dups) of this row, and see how many go to Fd and how many go to Fo
509:       PetscInt cur = 0;
510:       while (cur < nz) {
511:         PetscInt curColIdx = jbuf[cur];
512:         PetscInt dups      = 1;

514:         while (cur + dups < nz && jbuf[cur + dups] == curColIdx) dups++;
515:         if (curColIdx >= cstart && curColIdx < cend) {
516:           Fdi[curRowIdx]++;
517:           FdnzDups += dups;
518:         } else {
519:           Foi[curRowIdx]++;
520:           FonzDups += dups;
521:         }
522:         cur += dups;
523:       }

525:       FnzDups += nz;
526:       iter += dupRows; // Move to next unique row
527:     }

529:     Fdi = Fdi_h.data(); // restore Fdi, Foi and make them CSR
530:     Foi = Foi_h.data();
531:     for (PetscInt i = 0; i < Fm; i++) {
532:       Fdi[i + 1] += Fdi[i];
533:       Foi[i + 1] += Foi[i];
534:     }
535:     Fdnz = Fdi[Fm];
536:     Fonz = Foi[Fm];
537:     PetscCall(PetscFree2(sendCol, recvCol));

539:     // Allocate j, jmap, jperm for Fd and Fo
540:     MatColIdxKokkosViewHost Fdj_h(NoInit("Fdj_h"), Fdnz), Foj_h(NoInit("Foj_h"), Fonz);
541:     MatRowMapKokkosViewHost Fdjmap_h(NoInit("Fdjmap_h"), Fdnz + 1), Fojmap_h(NoInit("Fojmap_h"), Fonz + 1); // +1 to make csr
542:     MatRowMapKokkosViewHost Fdjperm_h(NoInit("Fdjperm_h"), FdnzDups), Fojperm_h(NoInit("Fojperm_h"), FonzDups);
543:     MatColIdxType          *Fdj = Fdj_h.data(), *Foj = Foj_h.data();
544:     MatRowMapType          *Fdjmap = Fdjmap_h.data(), *Fojmap = Fojmap_h.data();
545:     MatRowMapType          *Fdjperm = Fdjperm_h.data(), *Fojperm = Fojperm_h.data();

547:     // Scan recvColSorted[] again, and fill j, jmap, jperm for Fd and Fo
548:     Fdjmap[0] = 0;
549:     Fojmap[0] = 0;
550:     FnzDups   = 0;
551:     Fdnz      = 0;
552:     Fonz      = 0;
553:     iter      = 0; // iter over received rows
554:     while (iter < recvRowCnt) {
555:       PetscInt curRowIdx = irootloc[recvRowPerm[iter]]; // current row idx
556:       PetscInt dupRows   = 1;                           // It has this many contributing rows (of various lengths)
557:       PetscInt nz        = 0;                           // nz (with dups) in the current row

559:       while (iter + dupRows < recvRowCnt && irootloc[recvRowPerm[iter + dupRows]] == curRowIdx) dupRows++;
560:       for (PetscInt d = 0; d < dupRows; d++) {
561:         PetscInt i = recvRowPerm[iter + d];
562:         nz += recvRowLen[i + 1] - recvRowLen[i];
563:       }

565:       PetscInt *jbuf = recvColSorted + FnzDups;
566:       // Scan columns (in jbuf[0,nz) of this row, copy them and their permutation to j[] and jperm[] of Fd and Fo
567:       PetscInt cur = 0;
568:       while (cur < nz) {
569:         PetscInt curColIdx = jbuf[cur];
570:         PetscInt dups      = 1;

572:         while (cur + dups < nz && jbuf[cur + dups] == curColIdx) dups++;
573:         if (curColIdx >= cstart && curColIdx < cend) {
574:           Fdj[Fdnz]        = curColIdx - cstart; // easily convert to local
575:           Fdjmap[Fdnz + 1] = Fdjmap[Fdnz] + dups;
576:           for (PetscInt j = 0; j < dups; j++) Fdjperm[Fdjmap[Fdnz] + j] = recvNzPermSorted[FnzDups + j];
577:           FdnzDups += dups;
578:           Fdnz++;
579:         } else {
580:           Foj[Fonz]        = curColIdx; // in global
581:           Fojmap[Fonz + 1] = Fojmap[Fonz] + dups;
582:           for (PetscInt j = 0; j < dups; j++) Fojperm[Fojmap[Fonz] + j] = recvNzPermSorted[FnzDups + j];
583:           FonzDups += dups;
584:           Fonz++;
585:         }
586:         cur += dups;
587:         FnzDups += dups;
588:       }
589:       iter += dupRows; // Move to next unique row
590:     }
591:     PetscCall(PetscFree4(recvRowPerm, recvColSorted, recvNzPerm, recvNzPermSorted));
592:     PetscCall(PetscFree5(sendRowLen, recvRowLen, sdisp, rdisp, reqs));

594:     // Combine global column indices in garray1[] and Foj[]
595:     PetscInt n2, *garray2;

597:     PetscCall(ReduceTwoSetsOfGlobalIndices(n1, garray1, Fonz, Foj, &n2, &garray2, map));
598:     mm->sf       = reduceSF;
599:     mm->leafBuf  = MatScalarKokkosView(NoInit("leafBuf"), nleaves);
600:     mm->rootBuf  = MatScalarKokkosView(NoInit("rootBuf"), nroots);
601:     mm->garray   = garray2; // give ownership, so no free
602:     mm->n        = n2;
603:     mm->E_NzLeft = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), E_NzLeft_h);
604:     mm->Fdjmap   = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), Fdjmap_h);
605:     mm->Fdjperm  = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), Fdjperm_h);
606:     mm->Fojmap   = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), Fojmap_h);
607:     mm->Fojperm  = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), Fojperm_h);

609:     // Output Fd and Fo in KokkosCsrMatrix format
610:     MatScalarKokkosView Fda_d(NoInit("Fda_d"), Fdnz);
611:     MatRowMapKokkosView Fdi_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), Fdi_h);
612:     MatColIdxKokkosView Fdj_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), Fdj_h);
613:     MatScalarKokkosView Foa_d(NoInit("Foa_d"), Fonz);
614:     MatRowMapKokkosView Foi_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), Foi_h);
615:     MatColIdxKokkosView Foj_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), Foj_h);

617:     PetscCallCXX(mm->Fd = KokkosCsrMatrix("Fd", Fm, cend - cstart, Fdnz, Fda_d, Fdi_d, Fdj_d));
618:     PetscCallCXX(mm->Fo = KokkosCsrMatrix("Fo", Fm, n2, Fonz, Foa_d, Foi_d, Foj_d)); // Fo's column size is n2, length of garray2[]

620:     // Compute kernel launch parameters in merging E
621:     PetscInt teamSize, vectorLength, rowsPerTeam;

623:     teamSize = vectorLength = rowsPerTeam = -1;
624:     PetscCall(MatMergeGetLaunchParameters<DefaultExecutionSpace>(Em, Enz, -1, teamSize, vectorLength, rowsPerTeam));
625:     mm->E_TeamSize     = teamSize;
626:     mm->E_VectorLength = vectorLength;
627:     mm->E_RowsPerTeam  = rowsPerTeam;
628:   } else PetscCheck(reuse == MAT_REUSE_MATRIX, comm, PETSC_ERR_PLIB, "Unsupported MatReuse enum %d", reuse);

630:   // Handy aliases
631:   auto       &Aa           = A.values;
632:   auto       &Ba           = B.values;
633:   const auto &Ai           = A.graph.row_map;
634:   const auto &Bi           = B.graph.row_map;
635:   const auto &E_NzLeft     = mm->E_NzLeft;
636:   auto       &leafBuf      = mm->leafBuf;
637:   auto       &rootBuf      = mm->rootBuf;
638:   PetscSF     reduceSF     = mm->sf;
639:   PetscInt    Em           = A.numRows();
640:   PetscInt    teamSize     = mm->E_TeamSize;
641:   PetscInt    vectorLength = mm->E_VectorLength;
642:   PetscInt    rowsPerTeam  = mm->E_RowsPerTeam;
643:   PetscInt    workSets     = (Em + rowsPerTeam - 1) / rowsPerTeam;

645:   // Copy rows in A/B of E to leafBuf, then pass it to rootBuf
646:   PetscCallCXX(Kokkos::parallel_for(
647:     Kokkos::TeamPolicy<>(PetscGetKokkosExecutionSpace(), workSets, teamSize, vectorLength), KOKKOS_LAMBDA(const KokkosTeamMemberType &t) {
648:       Kokkos::parallel_for(Kokkos::TeamThreadRange(t, 0, rowsPerTeam), [&](PetscInt k) {
649:         PetscInt i = t.league_rank() * rowsPerTeam + k; // i-th row in F
650:         if (i < Em) {
651:           PetscInt disp   = Ai(i) + Bi(i);
652:           PetscInt alen   = Ai(i + 1) - Ai(i);
653:           PetscInt blen   = Bi(i + 1) - Bi(i);
654:           PetscInt nzleft = E_NzLeft(i);

656:           Kokkos::parallel_for(Kokkos::ThreadVectorRange(t, alen + blen), [&](PetscInt j) {
657:             MatScalar &val = leafBuf(disp + j);
658:             if (j < nzleft) { // B left
659:               val = Ba(Bi(i) + j);
660:             } else if (j < nzleft + alen) { // diag A
661:               val = Aa(Ai(i) + j - nzleft);
662:             } else { // B right
663:               val = Ba(Bi(i) + j - alen);
664:             }
665:           });
666:         }
667:       });
668:     }));
669:   PetscCall(PetscSFSynchronizeKokkos_Private(reduceSF, PETSC_TRUE));
670:   PetscCall(PetscSFReduceWithMemTypeBegin(reduceSF, MPIU_SCALAR, PETSC_MEMTYPE_KOKKOS, leafBuf.data(), PETSC_MEMTYPE_KOKKOS, rootBuf.data(), MPI_REPLACE));
671:   PetscFunctionReturn(PETSC_SUCCESS);
672: }

674: // To finish MatMPIAIJKokkosReduce.
675: static PetscErrorCode MatMPIAIJKokkosReduceEnd(MPI_Comm, KokkosCsrMatrix, KokkosCsrMatrix, PetscInt, PetscInt, const PetscInt *, PetscSF, MatReuse, PetscInt *, MatMatStruct_AtB *mm)
676: {
677:   auto       &leafBuf  = mm->leafBuf;
678:   auto       &rootBuf  = mm->rootBuf;
679:   auto       &Fda      = mm->Fd.values;
680:   const auto &Fdjmap   = mm->Fdjmap;
681:   const auto &Fdjperm  = mm->Fdjperm;
682:   auto        Fdnz     = mm->Fd.nnz();
683:   auto       &Foa      = mm->Fo.values;
684:   const auto &Fojmap   = mm->Fojmap;
685:   const auto &Fojperm  = mm->Fojperm;
686:   auto        Fonz     = mm->Fo.nnz();
687:   PetscSF     reduceSF = mm->sf;

689:   PetscFunctionBegin;
690:   PetscCall(PetscSFReduceEnd(reduceSF, MPIU_SCALAR, leafBuf.data(), rootBuf.data(), MPI_REPLACE));
691:   PetscCall(PetscSFSynchronizeKokkos_Private(reduceSF, PETSC_FALSE));

693:   // Reduce data in rootBuf to Fd and Fo
694:   PetscCallCXX(Kokkos::parallel_for(
695:     Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, Fdnz), KOKKOS_LAMBDA(const MatRowMapType i) {
696:       PetscScalar sum = 0.0;
697:       for (MatRowMapType k = Fdjmap(i); k < Fdjmap(i + 1); k++) sum += rootBuf(Fdjperm(k));
698:       Fda(i) = sum;
699:     }));

701:   PetscCallCXX(Kokkos::parallel_for(
702:     Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, Fonz), KOKKOS_LAMBDA(const MatRowMapType i) {
703:       PetscScalar sum = 0.0;
704:       for (MatRowMapType k = Fojmap(i); k < Fojmap(i + 1); k++) sum += rootBuf(Fojperm(k));
705:       Foa(i) = sum;
706:     }));
707:   PetscFunctionReturn(PETSC_SUCCESS);
708: }

710: /*
711:   MatMPIAIJKokkosBcast - Bcast local rows of a MPIAIJKOKKOS matrix (E) to produce a local matrix (F, stored in mm) in split form

713:   This is a complex routine. It is essentially the MPIAIJKOKKOS counterpart of MatGetBrowsOfAoCols_MPIAIJ, but supports
714:   device and involves various index mapping.

716:   In the given ownerSF, leaves correspond to rows in F, and roots correspond to rows in E. Roots may connect to multiple leaves.
717:   Suppose F's j-th row is connected to a root identified by PetscSFNode (k,i), it means we need to bcast the i-th row of E on rank k
718:   to j-th row of F. ownerSF is not an arbitrary SF, instead it is the Mvctx of another MPIAIJ matrix A that is able to perform A*E.
719:   F has the same column layout as E.

721:   Conceptually F has global column indices. In this routine, we spit F into diagonal Fd and off-diagonal Fo.
722:   Fd uses local column indices, which are easy to compute. We just need to subtract the "local column range start" from the global indices.
723:   Fo had global column indices at first. We will reduce them into local ones. In doing that, we also take into account the global
724:   column indices that E's off-diag block has. Let's say there are n1 such indices stored in garray1[]. We will reduce them along with
725:   column indices in Fo and update Fo with local indices.

727:    Input Parameters:
728: +   E       - the MPIAIJKOKKOS matrix
729: .   ownerSF - the ownership SF (insignificant in MAT_REUSE_MATRIX)
730: .   reuse   - either MAT_INITIAL_MATRIX or MAT_REUSE_MATRIX
731: -   mm      - to stash matproduct intermediate data structures

733:     Output Parameters:
734: +   map[n1] - allocated by caller. It maps garray1[] to garray2[]. See more at ReduceTwoSetsOfGlobalIndices.
735: -   mm      - contains various info, such as garray2[], Fd, Fo, etc.

737:     Notes:
738:     When reuse = MAT_REUSE_MATRIX, ownerSF, map are not significant.
739:     The routine is provide in split-phase form MatMPIAIJKokkosBcastBegin/End() to provide computation/communication opportunities.
740: */
741: static PetscErrorCode MatMPIAIJKokkosBcastBegin(Mat E, PetscSF ownerSF, MatReuse reuse, PetscInt *map, MatMatStruct_AB *mm)
742: {
743:   Mat_MPIAIJ       *empi = static_cast<Mat_MPIAIJ *>(E->data);
744:   Mat               A = empi->A, B = empi->B; // diag and off-diag
745:   Mat_SeqAIJKokkos *akok = static_cast<Mat_SeqAIJKokkos *>(A->spptr), *bkok = static_cast<Mat_SeqAIJKokkos *>(B->spptr);
746:   PetscInt          Em = E->rmap->n; // #local rows
747:   MPI_Comm          comm;

749:   PetscFunctionBegin;
750:   PetscCallMPI(PetscObjectGetComm((PetscObject)E, &comm));
751:   if (reuse == MAT_INITIAL_MATRIX) {
752:     Mat_SeqAIJ     *aseq = static_cast<Mat_SeqAIJ *>(A->data), *bseq = static_cast<Mat_SeqAIJ *>(B->data);
753:     PetscInt        n1 = B->cmap->n, *Ai = aseq->i, *Aj = aseq->j, *Bi = bseq->i, *Bj = bseq->j;
754:     const PetscInt *garray1 = empi->garray; // its size is n1
755:     PetscInt        cstart, cend;
756:     PetscSF         bcastSF;

758:     PetscCall(MatGetOwnershipRangeColumn(E, &cstart, &cend));

760:     // Count how many nonzeros of each row in E are in the left of the diag block [cstart,cend)
761:     PetscIntKokkosViewHost E_NzLeft_h(NoInit("E_NzLeft_h"), Em), E_RowLen_h(NoInit("E_RowLen_h"), Em);
762:     PetscInt              *E_NzLeft = E_NzLeft_h.data(), *E_RowLen = E_RowLen_h.data();
763:     for (PetscInt i = 0; i < Em; i++) {
764:       const PetscInt *first, *last, *it;
765:       PetscInt        count, step;
766:       // std::lower_bound(first,last,cstart), but need to use global column indices
767:       first = Bj + Bi[i];
768:       last  = Bj + Bi[i + 1];
769:       count = last - first;
770:       while (count > 0) {
771:         it   = first;
772:         step = count / 2;
773:         it += step;
774:         if (empi->garray[*it] < cstart) { // map local to global
775:           first = ++it;
776:           count -= step + 1;
777:         } else count = step;
778:       }
779:       E_NzLeft[i] = first - (Bj + Bi[i]);
780:       E_RowLen[i] = (Ai[i + 1] - Ai[i]) + (Bi[i + 1] - Bi[i]);
781:     }

783:     // Compute row pointer Fi of F
784:     PetscInt *Fi, Fm, Fnz;
785:     PetscCall(PetscSFGetGraph(ownerSF, NULL, &Fm, NULL, NULL)); // Fm = #rows of F = nleaves of ownerSF
786:     PetscCall(PetscMalloc1(Fm + 1, &Fi));
787:     Fi[0] = 0;
788:     PetscCall(PetscSFBcastWithMemTypeBegin(ownerSF, MPIU_INT, PETSC_MEMTYPE_HOST, E_RowLen, PETSC_MEMTYPE_HOST, &Fi[1], MPI_REPLACE));
789:     PetscCall(PetscSFBcastEnd(ownerSF, MPIU_INT, E_RowLen, &Fi[1], MPI_REPLACE));
790:     for (PetscInt i = 0; i < Fm; i++) Fi[i + 1] += Fi[i];
791:     Fnz = Fi[Fm];

793:     // Build the real PetscSF for bcasting E rows (buffer to buffer)
794:     const PetscMPIInt *iranks, *ranks;
795:     const PetscInt    *ioffset, *irootloc, *roffset;
796:     PetscMPIInt        niranks, nranks;
797:     PetscInt          *sdisp, *rdisp;
798:     MPI_Request       *reqs;
799:     PetscMPIInt        tag;

801:     PetscCall(PetscSFGetLeafRanks(ownerSF, &niranks, &iranks, &ioffset, &irootloc)); // get leaf ranks referencing roots on this process
802:     PetscCall(PetscSFGetRootRanks(ownerSF, &nranks, &ranks, &roffset, NULL, NULL));  // recv info
803:     PetscCall(PetscMalloc3(niranks + 1, &sdisp, nranks, &rdisp, niranks + nranks, &reqs));

805:     sdisp[0] = 0; // send displacement
806:     for (PetscInt i = 0; i < niranks; i++) {
807:       sdisp[i + 1] = sdisp[i];
808:       for (PetscInt j = ioffset[i]; j < ioffset[i + 1]; j++) {
809:         PetscInt r = irootloc[j]; // row to be sent
810:         sdisp[i + 1] += E_RowLen[r];
811:       }
812:     }

814:     PetscCallMPI(PetscCommGetNewTag(comm, &tag));
815:     for (PetscInt i = 0; i < nranks; i++) PetscCallMPI(MPIU_Irecv(&rdisp[i], 1, MPIU_INT, ranks[i], tag, comm, &reqs[i]));
816:     for (PetscInt i = 0; i < niranks; i++) PetscCallMPI(MPIU_Isend(&sdisp[i], 1, MPIU_INT, iranks[i], tag, comm, &reqs[nranks + i]));
817:     PetscCallMPI(MPI_Waitall(niranks + nranks, reqs, MPI_STATUSES_IGNORE));

819:     PetscInt     nleaves = Fnz;            // leaves are nonzeros I will receive
820:     PetscInt     nroots  = sdisp[niranks]; // roots are nonzeros I will send
821:     PetscSFNode *iremote;                  // give ownership to bcastSF
822:     PetscCall(PetscMalloc1(nleaves, &iremote));
823:     for (PetscInt i = 0; i < nranks; i++) { // for each sender rank
824:       PetscInt k = 0;
825:       for (PetscInt j = Fi[roffset[i]]; j < Fi[roffset[i + 1]]; j++) { // I will receive rows [roffset[i], roffset[i+1]) of F from ranks[i]
826:         iremote[j].rank  = ranks[i];
827:         iremote[j].index = rdisp[i] + k; // their root location
828:         k++;
829:       }
830:     }
831:     PetscCall(PetscSFCreate(comm, &bcastSF));
832:     PetscCall(PetscSFSetGraph(bcastSF, nroots, nleaves, NULL, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER));
833:     PetscCall(PetscFree3(sdisp, rdisp, reqs));

835:     // Build a plan (rowoffset, irootloc, E_NzLeft) to copy rows in E to rootdata of bcastSF in parallel
836:     PetscIntKokkosViewHost rowoffset_h(NoInit("rowoffset_h"), ioffset[niranks] + 1);
837:     PetscInt              *rowoffset = rowoffset_h.data(); // for each entry (row) indicated in irootloc[], we calculate its destinate offset in copying
838:     rowoffset[0]                     = 0;
839:     for (PetscInt i = 0; i < ioffset[niranks]; i++) rowoffset[i + 1] = rowoffset[i] + E_RowLen[irootloc[i]];

841:     // Copy (global) column indices of the needed rows in E to a buffer, and then bcast to Fj[]
842:     PetscInt *jbuf, *Fj;
843:     PetscCall(PetscMalloc2(nroots, &jbuf, Fnz, &Fj));
844:     for (PetscInt k = 0; k < ioffset[niranks]; k++) {
845:       PetscInt  i      = irootloc[k]; // row to be copied
846:       PetscInt *buf    = &jbuf[rowoffset[k]];
847:       PetscInt  nzLeft = E_NzLeft[i];
848:       PetscInt  alen = Ai[i + 1] - Ai[i], blen = Bi[i + 1] - Bi[i];
849:       for (PetscInt j = 0; j < alen + blen; j++) {
850:         if (j < nzLeft) {
851:           buf[j] = empi->garray[Bj[Bi[i] + j]]; // left B, in global
852:         } else if (j < nzLeft + alen) {
853:           buf[j] = Aj[Ai[i] + j - nzLeft] + cstart; // diag A, also in global
854:         } else {
855:           buf[j] = empi->garray[Bj[Bi[i] + j - alen]]; // right B, in global
856:         }
857:       }
858:     }
859:     PetscCall(PetscSFBcastWithMemTypeBegin(bcastSF, MPIU_INT, PETSC_MEMTYPE_HOST, jbuf, PETSC_MEMTYPE_HOST, Fj, MPI_REPLACE));
860:     PetscCall(PetscSFBcastEnd(bcastSF, MPIU_INT, jbuf, Fj, MPI_REPLACE));

862:     // Build a plan (i.e., F_NzLeft) to split F into Fd and Fo
863:     MatRowMapKokkosViewHost Fdi_h(NoInit("Fdi_h"), Fm + 1), Foi_h(NoInit("Foi_h"), Fm + 1); // row pointer of Fd, Fo
864:     MatColIdxKokkosViewHost F_NzLeft_h(NoInit("F_NzLeft_h"), Fm);                           // split each row of F into Left, Diag, Right. We only need to record #nz in Left and Diag.
865:     MatRowMapType          *Fdi = Fdi_h.data(), *Foi = Foi_h.data();
866:     MatColIdxType          *F_NzLeft = F_NzLeft_h.data();

868:     Fdi[0] = Foi[0] = 0;
869:     for (PetscInt i = 0; i < Fm; i++) {
870:       PetscInt *first, *last, *lb1, *lb2;
871:       // cut the row into: Left, [cstart, cend), Right
872:       first       = Fj + Fi[i];
873:       last        = Fj + Fi[i + 1];
874:       lb1         = std::lower_bound(first, last, cstart);
875:       F_NzLeft[i] = lb1 - first;
876:       lb2         = std::lower_bound(first, last, cend);
877:       Fdi[i + 1]  = lb2 - lb1;                        // row i length in Fdi
878:       Foi[i + 1]  = (Fi[i + 1] - Fi[i]) - Fdi[i + 1]; // row i length in Foi
879:     }
880:     for (PetscInt i = 0; i < Fm; i++) {
881:       Fdi[i + 1] += Fdi[i];
882:       Foi[i + 1] += Foi[i];
883:     }

885:     // Fill Fdj[] and Foj[], i.e., columns of Fd and Fo. Fdj[] are local, but Foj[] are not yet.
886:     PetscInt                Fdnz = Fdi[Fm], Fonz = Foi[Fm];
887:     MatColIdxKokkosViewHost Fdj_h(NoInit("Fdj_h"), Fdnz), Foj_h(NoInit("Foj_h"), Fonz);
888:     MatColIdxType          *Fdj = Fdj_h.data(), *Foj = Foj_h.data(), gid;

890:     for (PetscInt i = 0; i < Fm; i++) {
891:       PetscInt nzLeft = F_NzLeft[i];
892:       PetscInt len    = Fdi[i + 1] - Fdi[i]; // diag row len
893:       for (PetscInt j = 0; j < Fi[i + 1] - Fi[i]; j++) {
894:         gid = Fj[Fi[i] + j];
895:         if (j < nzLeft) { // left, in global
896:           Foj[Foi[i] + j] = gid;
897:         } else if (j < nzLeft + len) { // diag, in local
898:           Fdj[Fdi[i] + j - nzLeft] = gid - cstart;
899:         } else { // right, in global
900:           Foj[Foi[i] + j - len] = gid;
901:         }
902:       }
903:     }
904:     PetscCall(PetscFree2(jbuf, Fj));
905:     PetscCall(PetscFree(Fi));

907:     // Reduce global indices in Foj[] and garray1[] into local ones
908:     PetscInt n2, *garray2;
909:     PetscCall(ReduceTwoSetsOfGlobalIndices(n1, garray1, Fonz, Foj, &n2, &garray2, map));

911:     // Record the plans built above, for reuse
912:     PetscIntKokkosViewHost tmp(const_cast<PetscInt *>(irootloc), ioffset[niranks]); // irootloc[] is owned by ownerSF. We create a copy for safety
913:     PetscIntKokkosViewHost irootloc_h(NoInit("irootloc_h"), ioffset[niranks]);
914:     Kokkos::deep_copy(irootloc_h, tmp);
915:     mm->sf        = bcastSF;
916:     mm->E_NzLeft  = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), E_NzLeft_h);
917:     mm->F_NzLeft  = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), F_NzLeft_h);
918:     mm->irootloc  = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), irootloc_h);
919:     mm->rowoffset = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), rowoffset_h);
920:     mm->rootBuf   = MatScalarKokkosView(NoInit("rootBuf"), nroots);
921:     mm->leafBuf   = MatScalarKokkosView(NoInit("leafBuf"), nleaves);
922:     mm->garray    = garray2;
923:     mm->n         = n2;

925:     // Output Fd and Fo in KokkosCsrMatrix format
926:     MatScalarKokkosView Fda_d(NoInit("Fda_d"), Fdnz), Foa_d(NoInit("Foa_d"), Fonz);
927:     MatRowMapKokkosView Fdi_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), Fdi_h);
928:     MatColIdxKokkosView Fdj_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), Fdj_h);
929:     MatRowMapKokkosView Foi_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), Foi_h);
930:     MatColIdxKokkosView Foj_d = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), Foj_h);

932:     PetscCallCXX(mm->Fd = KokkosCsrMatrix("Fd", Fm, cend - cstart, Fdnz, Fda_d, Fdi_d, Fdj_d));
933:     PetscCallCXX(mm->Fo = KokkosCsrMatrix("Fo", Fm, n2, Fonz, Foa_d, Foi_d, Foj_d));

935:     // Compute kernel launch parameters in merging E or splitting F
936:     PetscInt teamSize, vectorLength, rowsPerTeam;

938:     teamSize = vectorLength = rowsPerTeam = -1;
939:     PetscCall(MatMergeGetLaunchParameters<DefaultExecutionSpace>(mm->irootloc.extent(0), mm->rootBuf.extent(0), -1, teamSize, vectorLength, rowsPerTeam));
940:     mm->E_TeamSize     = teamSize;
941:     mm->E_VectorLength = vectorLength;
942:     mm->E_RowsPerTeam  = rowsPerTeam;

944:     teamSize = vectorLength = rowsPerTeam = -1;
945:     PetscCall(MatMergeGetLaunchParameters<DefaultExecutionSpace>(Fm, Fnz, -1, teamSize, vectorLength, rowsPerTeam));
946:     mm->F_TeamSize     = teamSize;
947:     mm->F_VectorLength = vectorLength;
948:     mm->F_RowsPerTeam  = rowsPerTeam;
949:   } else PetscCheck(reuse == MAT_REUSE_MATRIX, comm, PETSC_ERR_PLIB, "Unsupported MatReuse enum %d", reuse);

951:   // Sync E's value to device
952:   PetscCall(KokkosDualViewSyncDevice(akok->a_dual, PetscGetKokkosExecutionSpace()));
953:   PetscCall(KokkosDualViewSyncDevice(bkok->a_dual, PetscGetKokkosExecutionSpace()));

955:   // Handy aliases
956:   const auto &Aa = akok->a_dual.view_device();
957:   const auto &Ba = bkok->a_dual.view_device();
958:   const auto &Ai = akok->i_dual.view_device();
959:   const auto &Bi = bkok->i_dual.view_device();

961:   // Fetch the plans
962:   PetscIntKokkosView  &E_NzLeft  = mm->E_NzLeft;
963:   PetscSF             &bcastSF   = mm->sf;
964:   MatScalarKokkosView &rootBuf   = mm->rootBuf;
965:   MatScalarKokkosView &leafBuf   = mm->leafBuf;
966:   PetscIntKokkosView  &irootloc  = mm->irootloc;
967:   PetscIntKokkosView  &rowoffset = mm->rowoffset;

969:   PetscInt teamSize     = mm->E_TeamSize;
970:   PetscInt vectorLength = mm->E_VectorLength;
971:   PetscInt rowsPerTeam  = mm->E_RowsPerTeam;
972:   PetscInt workSets     = (irootloc.extent(0) + rowsPerTeam - 1) / rowsPerTeam;

974:   // Copy rows in A/B of E to rootBuf, then bcast it to leafBuf
975:   PetscCallCXX(Kokkos::parallel_for(
976:     Kokkos::TeamPolicy<>(PetscGetKokkosExecutionSpace(), workSets, teamSize, vectorLength), KOKKOS_LAMBDA(const KokkosTeamMemberType &t) {
977:       Kokkos::parallel_for(Kokkos::TeamThreadRange(t, 0, rowsPerTeam), [&](PetscInt k) {
978:         size_t r = t.league_rank() * rowsPerTeam + k; // r-th entry in irootloc[]
979:         if (r < irootloc.extent(0)) {
980:           PetscInt i      = irootloc(r); // row i of E
981:           PetscInt disp   = rowoffset(r);
982:           PetscInt alen   = Ai(i + 1) - Ai(i);
983:           PetscInt blen   = Bi(i + 1) - Bi(i);
984:           PetscInt nzleft = E_NzLeft(i);

986:           Kokkos::parallel_for(Kokkos::ThreadVectorRange(t, alen + blen), [&](PetscInt j) {
987:             if (j < nzleft) { // B left
988:               rootBuf(disp + j) = Ba(Bi(i) + j);
989:             } else if (j < nzleft + alen) { // diag A
990:               rootBuf(disp + j) = Aa(Ai(i) + j - nzleft);
991:             } else { // B right
992:               rootBuf(disp + j) = Ba(Bi(i) + j - alen);
993:             }
994:           });
995:         }
996:       });
997:     }));
998:   PetscCall(PetscSFSynchronizeKokkos_Private(bcastSF, PETSC_TRUE));
999:   PetscCall(PetscSFBcastWithMemTypeBegin(bcastSF, MPIU_SCALAR, PETSC_MEMTYPE_KOKKOS, rootBuf.data(), PETSC_MEMTYPE_KOKKOS, leafBuf.data(), MPI_REPLACE));
1000:   PetscFunctionReturn(PETSC_SUCCESS);
1001: }

1003: // To finish MatMPIAIJKokkosBcast.
1004: static PetscErrorCode MatMPIAIJKokkosBcastEnd(Mat, PetscSF, MatReuse, PetscInt *, MatMatStruct_AB *mm)
1005: {
1006:   PetscFunctionBegin;
1007:   const auto &Fd  = mm->Fd;
1008:   const auto &Fo  = mm->Fo;
1009:   const auto &Fdi = Fd.graph.row_map;
1010:   const auto &Foi = Fo.graph.row_map;
1011:   auto       &Fda = Fd.values;
1012:   auto       &Foa = Fo.values;
1013:   auto        Fm  = Fd.numRows();

1015:   PetscIntKokkosView  &F_NzLeft     = mm->F_NzLeft;
1016:   PetscSF             &bcastSF      = mm->sf;
1017:   MatScalarKokkosView &rootBuf      = mm->rootBuf;
1018:   MatScalarKokkosView &leafBuf      = mm->leafBuf;
1019:   PetscInt             teamSize     = mm->F_TeamSize;
1020:   PetscInt             vectorLength = mm->F_VectorLength;
1021:   PetscInt             rowsPerTeam  = mm->F_RowsPerTeam;
1022:   PetscInt             workSets     = (Fm + rowsPerTeam - 1) / rowsPerTeam;

1024:   PetscCall(PetscSFBcastEnd(bcastSF, MPIU_SCALAR, rootBuf.data(), leafBuf.data(), MPI_REPLACE));
1025:   PetscCall(PetscSFSynchronizeKokkos_Private(bcastSF, PETSC_FALSE));

1027:   // Update Fda and Foa with new data in leafBuf (as if it is Fa)
1028:   PetscCallCXX(Kokkos::parallel_for(
1029:     Kokkos::TeamPolicy<>(PetscGetKokkosExecutionSpace(), workSets, teamSize, vectorLength), KOKKOS_LAMBDA(const KokkosTeamMemberType &t) {
1030:       Kokkos::parallel_for(Kokkos::TeamThreadRange(t, 0, rowsPerTeam), [&](PetscInt k) {
1031:         PetscInt i = t.league_rank() * rowsPerTeam + k; // i-th row in F
1032:         if (i < Fm) {
1033:           PetscInt nzLeft = F_NzLeft(i);
1034:           PetscInt alen   = Fdi(i + 1) - Fdi(i);
1035:           PetscInt blen   = Foi(i + 1) - Foi(i);
1036:           PetscInt Fii    = Fdi(i) + Foi(i);

1038:           Kokkos::parallel_for(Kokkos::ThreadVectorRange(t, alen + blen), [&](PetscInt j) {
1039:             PetscScalar val = leafBuf(Fii + j);
1040:             if (j < nzLeft) { // left
1041:               Foa(Foi(i) + j) = val;
1042:             } else if (j < nzLeft + alen) { // diag
1043:               Fda(Fdi(i) + j - nzLeft) = val;
1044:             } else { // right
1045:               Foa(Foi(i) + j - alen) = val;
1046:             }
1047:           });
1048:         }
1049:       });
1050:     }));
1051:   PetscFunctionReturn(PETSC_SUCCESS);
1052: }

1054: static PetscErrorCode MatProductSymbolic_MPIAIJKokkos_AtB(Mat_Product *, Mat A, Mat B, MatMatStruct_AtB *mm)
1055: {
1056:   Mat_MPIAIJ     *ampi = static_cast<Mat_MPIAIJ *>(A->data);
1057:   Mat_MPIAIJ     *bmpi = static_cast<Mat_MPIAIJ *>(B->data);
1058:   KokkosCsrMatrix Adt, Aot, Ad, Ao, Bd, Bo;
1059:   PetscInt        cstart, cend;
1060:   MPI_Comm        comm;

1062:   PetscFunctionBegin;
1063:   PetscCall(PetscObjectGetComm((PetscObject)B, &comm));
1064:   PetscCall(MatSeqAIJKokkosGenerateTranspose_Private(ampi->A, &Adt));
1065:   PetscCall(MatSeqAIJKokkosGenerateTranspose_Private(ampi->B, &Aot));
1066:   PetscCall(MatSeqAIJKokkosGetKokkosCsrMatrix(ampi->A, &Ad));
1067:   PetscCall(MatSeqAIJKokkosGetKokkosCsrMatrix(ampi->B, &Ao));
1068:   PetscCall(MatSeqAIJKokkosGetKokkosCsrMatrix(bmpi->A, &Bd));
1069:   PetscCall(MatSeqAIJKokkosGetKokkosCsrMatrix(bmpi->B, &Bo));

1071:   // TODO: add command line options to select spgemm algorithms
1072:   auto spgemm_alg = KokkosSparse::SPGEMMAlgorithm::SPGEMM_DEFAULT; // default is TPL if enabled, otherwise KK

1074:   PetscCallCXX(mm->kh1.create_spgemm_handle(spgemm_alg));
1075:   PetscCallCXX(mm->kh2.create_spgemm_handle(spgemm_alg));
1076:   PetscCallCXX(mm->kh3.create_spgemm_handle(spgemm_alg));
1077:   PetscCallCXX(mm->kh4.create_spgemm_handle(spgemm_alg));

1079:   // Aot * (B's diag + B's off-diag)
1080:   PetscCallCXX(KokkosSparse::spgemm_symbolic(mm->kh3, Aot, false, Bd, false, mm->C3));
1081:   PetscCallCXX(KokkosSparse::spgemm_symbolic(mm->kh4, Aot, false, Bo, false, mm->C4));
1082:   // KK spgemm_symbolic() only populates the result's row map, but not its columns.
1083:   // TODO: Remove the fake spgemm_numeric() after KK fixed this problem.
1084:   PetscCallCXX(KokkosSparse::spgemm_numeric(mm->kh3, Aot, false, Bd, false, mm->C3));
1085:   PetscCallCXX(KokkosSparse::spgemm_numeric(mm->kh4, Aot, false, Bo, false, mm->C4));
1086: #if PETSC_PKG_KOKKOS_KERNELS_VERSION_LT(4, 0, 0)

1088:   PetscCallCXX(sort_crs_matrix(mm->C3));
1089:   PetscCallCXX(sort_crs_matrix(mm->C4));
1090: #endif

1092:   // Reduce E (i.e., C3 and C4)'s rows to form F, and overlap the communication
1093:   PetscIntKokkosViewHost map_h(NoInit("map_h"), bmpi->B->cmap->n);
1094:   PetscCall(MatGetOwnershipRangeColumn(B, &cstart, &cend));
1095:   PetscCall(MatMPIAIJKokkosReduceBegin(comm, mm->C3, mm->C4, cstart, cend, bmpi->garray, ampi->Mvctx, MAT_INITIAL_MATRIX, map_h.data(), mm));

1097:   // Adt * (B's diag + B's off-diag)
1098:   PetscCallCXX(KokkosSparse::spgemm_symbolic(mm->kh1, Adt, false, Bd, false, mm->C1));
1099:   PetscCallCXX(KokkosSparse::spgemm_symbolic(mm->kh2, Adt, false, Bo, false, mm->C2_mid));
1100:   PetscCallCXX(KokkosSparse::spgemm_numeric(mm->kh1, Adt, false, Bd, false, mm->C1));
1101:   PetscCallCXX(KokkosSparse::spgemm_numeric(mm->kh2, Adt, false, Bo, false, mm->C2_mid));
1102: #if PETSC_PKG_KOKKOS_KERNELS_VERSION_LT(4, 0, 0)
1103:   PetscCallCXX(sort_crs_matrix(mm->C1));
1104:   PetscCallCXX(sort_crs_matrix(mm->C2_mid));
1105: #endif

1107:   PetscCall(MatMPIAIJKokkosReduceEnd(comm, mm->C3, mm->C4, cstart, cend, bmpi->garray, ampi->Mvctx, MAT_INITIAL_MATRIX, map_h.data(), mm));

1109:   // Create C2, which shares a, i arrays with C2_mid, but with new column indices and potentially larger column size
1110:   MatColIdxKokkosView oldj = mm->C2_mid.graph.entries, newj(NoInit("j"), oldj.extent(0));
1111:   PetscIntKokkosView  map  = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), map_h);
1112:   PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, oldj.extent(0)), KOKKOS_LAMBDA(const PetscInt i) { newj(i) = map(oldj(i)); }));
1113:   PetscCallCXX(mm->C2 = KokkosCsrMatrix("C2", mm->C2_mid.numRows(), mm->n /*new column size*/, mm->C2_mid.nnz(), mm->C2_mid.values, mm->C2_mid.graph.row_map, newj));

1115:   // C = (C1+Fd, C2+Fo)
1116:   PetscCallCXX(mm->kh1.create_spadd_handle(true)); // C1, Fd are sorted
1117:   PetscCallCXX(mm->kh2.create_spadd_handle(true)); // C2, Fo are sorted
1118:   PetscCallCXX(KokkosSparse::spadd_symbolic(&mm->kh1, mm->C1, mm->Fd, mm->Cd));
1119:   PetscCallCXX(KokkosSparse::spadd_symbolic(&mm->kh2, mm->C2, mm->Fo, mm->Co));
1120:   PetscCallCXX(KokkosSparse::spadd_numeric(&mm->kh1, 1.0, mm->C1, 1.0, mm->Fd, mm->Cd));
1121:   PetscCallCXX(KokkosSparse::spadd_numeric(&mm->kh2, 1.0, mm->C2, 1.0, mm->Fo, mm->Co));
1122:   PetscFunctionReturn(PETSC_SUCCESS);
1123: }

1125: static PetscErrorCode MatProductNumeric_MPIAIJKokkos_AtB(Mat_Product *, Mat A, Mat B, MatMatStruct_AtB *mm)
1126: {
1127:   Mat_MPIAIJ     *ampi = static_cast<Mat_MPIAIJ *>(A->data);
1128:   Mat_MPIAIJ     *bmpi = static_cast<Mat_MPIAIJ *>(B->data);
1129:   KokkosCsrMatrix Adt, Aot, Bd, Bo;
1130:   MPI_Comm        comm;

1132:   PetscFunctionBegin;
1133:   PetscCall(PetscObjectGetComm((PetscObject)B, &comm));
1134:   PetscCall(MatSeqAIJKokkosGenerateTranspose_Private(ampi->A, &Adt));
1135:   PetscCall(MatSeqAIJKokkosGenerateTranspose_Private(ampi->B, &Aot));
1136:   PetscCall(MatSeqAIJKokkosGetKokkosCsrMatrix(bmpi->A, &Bd));
1137:   PetscCall(MatSeqAIJKokkosGetKokkosCsrMatrix(bmpi->B, &Bo));

1139:   // Aot * (B's diag + B's off-diag)
1140:   PetscCallCXX(KokkosSparse::spgemm_numeric(mm->kh3, Aot, false, Bd, false, mm->C3));
1141:   PetscCallCXX(KokkosSparse::spgemm_numeric(mm->kh4, Aot, false, Bo, false, mm->C4));

1143:   // Reduce E (i.e., C3 and C4)'s rows to form F, and overlap the communication
1144:   PetscCall(MatMPIAIJKokkosReduceBegin(comm, mm->C3, mm->C4, 0, 0, NULL, NULL, MAT_REUSE_MATRIX, NULL, mm));

1146:   // Adt * (B's diag + B's off-diag)
1147:   PetscCallCXX(KokkosSparse::spgemm_numeric(mm->kh1, Adt, false, Bd, false, mm->C1));
1148:   PetscCallCXX(KokkosSparse::spgemm_numeric(mm->kh2, Adt, false, Bo, false, mm->C2_mid));

1150:   PetscCall(MatMPIAIJKokkosReduceEnd(comm, mm->C3, mm->C4, 0, 0, NULL, NULL, MAT_REUSE_MATRIX, NULL, mm));

1152:   // C = (C1+Fd, C2+Fo)
1153:   PetscCallCXX(KokkosSparse::spadd_numeric(&mm->kh1, 1.0, mm->C1, 1.0, mm->Fd, mm->Cd));
1154:   PetscCallCXX(KokkosSparse::spadd_numeric(&mm->kh2, 1.0, mm->C2, 1.0, mm->Fo, mm->Co));
1155:   PetscFunctionReturn(PETSC_SUCCESS);
1156: }

1158: /* MatProductSymbolic_MPIAIJKokkos_AB - AB flavor of MatProductSymbolic_MPIAIJKokkos

1160:   Input Parameters:
1161: +  product  - Mat_Product which carried out the computation. Passed in to access info about this mat product.
1162: .  A        - an MPIAIJKOKKOS matrix
1163: .  B        - an MPIAIJKOKKOS matrix
1164: -  mm       - a struct used to stash intermediate data when computing AB. Persist from symbolic to numeric operations.
1165: */
1166: static PetscErrorCode MatProductSymbolic_MPIAIJKokkos_AB(Mat_Product *, Mat A, Mat B, MatMatStruct_AB *mm)
1167: {
1168:   Mat_MPIAIJ     *ampi = static_cast<Mat_MPIAIJ *>(A->data);
1169:   Mat_MPIAIJ     *bmpi = static_cast<Mat_MPIAIJ *>(B->data);
1170:   KokkosCsrMatrix Ad, Ao, Bd, Bo;

1172:   PetscFunctionBegin;
1173:   PetscCall(MatSeqAIJKokkosGetKokkosCsrMatrix(ampi->A, &Ad));
1174:   PetscCall(MatSeqAIJKokkosGetKokkosCsrMatrix(ampi->B, &Ao));
1175:   PetscCall(MatSeqAIJKokkosGetKokkosCsrMatrix(bmpi->A, &Bd));
1176:   PetscCall(MatSeqAIJKokkosGetKokkosCsrMatrix(bmpi->B, &Bo));

1178:   // TODO: add command line options to select spgemm algorithms
1179:   auto spgemm_alg = KokkosSparse::SPGEMMAlgorithm::SPGEMM_DEFAULT; // default is TPL if enabled, otherwise KK

1181:   mm->kh1.create_spgemm_handle(spgemm_alg);
1182:   mm->kh2.create_spgemm_handle(spgemm_alg);
1183:   mm->kh3.create_spgemm_handle(spgemm_alg);
1184:   mm->kh4.create_spgemm_handle(spgemm_alg);

1186:   // Bcast B's rows to form F, and overlap the communication
1187:   PetscIntKokkosViewHost map_h(NoInit("map_h"), bmpi->B->cmap->n);
1188:   PetscCall(MatMPIAIJKokkosBcastBegin(B, ampi->Mvctx, MAT_INITIAL_MATRIX, map_h.data(), mm));

1190:   // A's diag * (B's diag + B's off-diag)
1191:   PetscCallCXX(KokkosSparse::spgemm_symbolic(mm->kh1, Ad, false, Bd, false, mm->C1));
1192:   PetscCallCXX(KokkosSparse::spgemm_symbolic(mm->kh2, Ad, false, Bo, false, mm->C2_mid)); // C2 aliases with C2_mid, except with new column indices
1193:   // KK spgemm_symbolic() only populates the result's row map, but not its columns.
1194:   // TODO: Remove the fake spgemm_numeric() after KK fixed this problem.
1195:   PetscCallCXX(KokkosSparse::spgemm_numeric(mm->kh1, Ad, false, Bd, false, mm->C1));
1196:   PetscCallCXX(KokkosSparse::spgemm_numeric(mm->kh2, Ad, false, Bo, false, mm->C2_mid));
1197: #if PETSC_PKG_KOKKOS_KERNELS_VERSION_LT(4, 0, 0)
1198:   PetscCallCXX(sort_crs_matrix(mm->C1));
1199:   PetscCallCXX(sort_crs_matrix(mm->C2_mid));
1200: #endif

1202:   PetscCall(MatMPIAIJKokkosBcastEnd(B, ampi->Mvctx, MAT_INITIAL_MATRIX, map_h.data(), mm));

1204:   // A's off-diag * (F's diag + F's off-diag)
1205:   PetscCallCXX(KokkosSparse::spgemm_symbolic(mm->kh3, Ao, false, mm->Fd, false, mm->C3));
1206:   PetscCallCXX(KokkosSparse::spgemm_numeric(mm->kh3, Ao, false, mm->Fd, false, mm->C3));
1207:   PetscCallCXX(KokkosSparse::spgemm_symbolic(mm->kh4, Ao, false, mm->Fo, false, mm->C4));
1208:   PetscCallCXX(KokkosSparse::spgemm_numeric(mm->kh4, Ao, false, mm->Fo, false, mm->C4));
1209: #if PETSC_PKG_KOKKOS_KERNELS_VERSION_LT(4, 0, 0)
1210:   PetscCallCXX(sort_crs_matrix(mm->C3));
1211:   PetscCallCXX(sort_crs_matrix(mm->C4));
1212: #endif

1214:   // Create C2, which shares a, i arrays with C2_mid, but with new column indices and potentially larger column size
1215:   MatColIdxKokkosView oldj = mm->C2_mid.graph.entries, newj(NoInit("j"), oldj.extent(0));
1216:   PetscIntKokkosView  map  = Kokkos::create_mirror_view_and_copy(DefaultMemorySpace(), map_h);
1217:   PetscCallCXX(Kokkos::parallel_for(Kokkos::RangePolicy<>(PetscGetKokkosExecutionSpace(), 0, oldj.extent(0)), KOKKOS_LAMBDA(const PetscInt i) { newj(i) = map(oldj(i)); }));
1218:   mm->C2 = KokkosCsrMatrix("C2", mm->C2_mid.numRows(), mm->n /*new column size*/, mm->C2_mid.nnz(), mm->C2_mid.values, mm->C2_mid.graph.row_map, newj);

1220:   // C = (Cd, Co) = (C1+C3, C2+C4)
1221:   mm->kh1.create_spadd_handle(true); // C1, C3 are sorted
1222:   mm->kh2.create_spadd_handle(true); // C2, C4 are sorted
1223:   PetscCallCXX(KokkosSparse::spadd_symbolic(&mm->kh1, mm->C1, mm->C3, mm->Cd));
1224:   PetscCallCXX(KokkosSparse::spadd_symbolic(&mm->kh2, mm->C2, mm->C4, mm->Co));
1225:   PetscCallCXX(KokkosSparse::spadd_numeric(&mm->kh1, 1.0, mm->C1, 1.0, mm->C3, mm->Cd));
1226:   PetscCallCXX(KokkosSparse::spadd_numeric(&mm->kh2, 1.0, mm->C2, 1.0, mm->C4, mm->Co));
1227:   PetscFunctionReturn(PETSC_SUCCESS);
1228: }

1230: static PetscErrorCode MatProductNumeric_MPIAIJKokkos_AB(Mat_Product *, Mat A, Mat B, MatMatStruct_AB *mm)
1231: {
1232:   Mat_MPIAIJ     *ampi = static_cast<Mat_MPIAIJ *>(A->data);
1233:   Mat_MPIAIJ     *bmpi = static_cast<Mat_MPIAIJ *>(B->data);
1234:   KokkosCsrMatrix Ad, Ao, Bd, Bo;

1236:   PetscFunctionBegin;
1237:   PetscCall(MatSeqAIJKokkosGetKokkosCsrMatrix(ampi->A, &Ad));
1238:   PetscCall(MatSeqAIJKokkosGetKokkosCsrMatrix(ampi->B, &Ao));
1239:   PetscCall(MatSeqAIJKokkosGetKokkosCsrMatrix(bmpi->A, &Bd));
1240:   PetscCall(MatSeqAIJKokkosGetKokkosCsrMatrix(bmpi->B, &Bo));

1242:   // Bcast B's rows to form F, and overlap the communication
1243:   PetscCall(MatMPIAIJKokkosBcastBegin(B, NULL, MAT_REUSE_MATRIX, NULL, mm));

1245:   // A's diag * (B's diag + B's off-diag)
1246:   PetscCallCXX(KokkosSparse::spgemm_numeric(mm->kh1, Ad, false, Bd, false, mm->C1));
1247:   PetscCallCXX(KokkosSparse::spgemm_numeric(mm->kh2, Ad, false, Bo, false, mm->C2_mid));

1249:   PetscCall(MatMPIAIJKokkosBcastEnd(B, NULL, MAT_REUSE_MATRIX, NULL, mm));

1251:   // A's off-diag * (F's diag + F's off-diag)
1252:   PetscCallCXX(KokkosSparse::spgemm_numeric(mm->kh3, Ao, false, mm->Fd, false, mm->C3));
1253:   PetscCallCXX(KokkosSparse::spgemm_numeric(mm->kh4, Ao, false, mm->Fo, false, mm->C4));

1255:   // C = (Cd, Co) = (C1+C3, C2+C4)
1256:   PetscCallCXX(KokkosSparse::spadd_numeric(&mm->kh1, 1.0, mm->C1, 1.0, mm->C3, mm->Cd));
1257:   PetscCallCXX(KokkosSparse::spadd_numeric(&mm->kh2, 1.0, mm->C2, 1.0, mm->C4, mm->Co));
1258:   PetscFunctionReturn(PETSC_SUCCESS);
1259: }

1261: static PetscErrorCode MatProductNumeric_MPIAIJKokkos(Mat C)
1262: {
1263:   Mat_MPIAIJ                 *cmpi = static_cast<Mat_MPIAIJ *>(C->data);
1264:   Mat_Product                *product;
1265:   MatProductCtx_MPIAIJKokkos *pdata;
1266:   MatProductType              ptype;
1267:   Mat                         A, B;

1269:   PetscFunctionBegin;
1270:   MatCheckProduct(C, 1); // make sure C is a product
1271:   product = C->product;
1272:   pdata   = static_cast<MatProductCtx_MPIAIJKokkos *>(product->data);
1273:   ptype   = product->type;
1274:   A       = product->A;
1275:   B       = product->B;

1277:   // See if numeric has already been done in symbolic (e.g., user calls MatMatMult(A,B,MAT_INITIAL_MATRIX,..,C)).
1278:   // If yes, skip the numeric, but reset the flag so that next time when user calls MatMatMult(E,F,MAT_REUSE_MATRIX,..,C),
1279:   // we still do numeric.
1280:   if (pdata->reusesym) { // numeric reuses results from symbolic
1281:     pdata->reusesym = PETSC_FALSE;
1282:     PetscFunctionReturn(PETSC_SUCCESS);
1283:   }

1285:   if (ptype == MATPRODUCT_AB) {
1286:     PetscCall(MatProductNumeric_MPIAIJKokkos_AB(product, A, B, pdata->mmAB));
1287:   } else if (ptype == MATPRODUCT_AtB) {
1288:     PetscCall(MatProductNumeric_MPIAIJKokkos_AtB(product, A, B, pdata->mmAtB));
1289:   } else if (ptype == MATPRODUCT_PtAP) { // BtAB, computed by Z = AB; C= BtZ
1290:     PetscCall(MatProductNumeric_MPIAIJKokkos_AB(product, A, B, pdata->mmAB));
1291:     PetscCall(MatProductNumeric_MPIAIJKokkos_AtB(product, B, pdata->Z, pdata->mmAtB));
1292:   }
1293:   PetscCall(MatSeqAIJKokkosModifyDevice(cmpi->A)); // mark that A, B on device are modified
1294:   PetscCall(MatSeqAIJKokkosModifyDevice(cmpi->B));
1295:   PetscFunctionReturn(PETSC_SUCCESS);
1296: }

1298: static PetscErrorCode MatProductSymbolic_MPIAIJKokkos(Mat C)
1299: {
1300:   Mat                         A, B;
1301:   Mat_Product                *product;
1302:   MatProductType              ptype;
1303:   MatProductCtx_MPIAIJKokkos *pdata;
1304:   MatMatStruct               *mm = NULL;
1305:   PetscInt                    m, n, M, N;
1306:   Mat                         Cd, Co;
1307:   MPI_Comm                    comm;
1308:   Mat_MPIAIJ                 *mpiaij;
1309:   const PetscBool             nooffprocentries = C->nooffprocentries;

1311:   PetscFunctionBegin;
1312:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
1313:   MatCheckProduct(C, 1);
1314:   product = C->product;
1315:   PetscCheck(!product->data, comm, PETSC_ERR_PLIB, "Product data not empty");
1316:   ptype = product->type;
1317:   A     = product->A;
1318:   B     = product->B;

1320:   switch (ptype) {
1321:   case MATPRODUCT_AB:
1322:     m = A->rmap->n;
1323:     n = B->cmap->n;
1324:     M = A->rmap->N;
1325:     N = B->cmap->N;
1326:     break;
1327:   case MATPRODUCT_AtB:
1328:     m = A->cmap->n;
1329:     n = B->cmap->n;
1330:     M = A->cmap->N;
1331:     N = B->cmap->N;
1332:     break;
1333:   case MATPRODUCT_PtAP:
1334:     m = B->cmap->n;
1335:     n = B->cmap->n;
1336:     M = B->cmap->N;
1337:     N = B->cmap->N;
1338:     break; /* BtAB */
1339:   default:
1340:     SETERRQ(comm, PETSC_ERR_PLIB, "Not for product type %s", MatProductTypes[ptype]);
1341:   }

1343:   PetscCall(MatSetSizes(C, m, n, M, N));
1344:   PetscCall(PetscLayoutSetUp(C->rmap));
1345:   PetscCall(PetscLayoutSetUp(C->cmap));
1346:   PetscCall(MatSetType(C, ((PetscObject)A)->type_name));

1348:   pdata           = new MatProductCtx_MPIAIJKokkos();
1349:   pdata->reusesym = product->api_user;

1351:   if (ptype == MATPRODUCT_AB) {
1352:     auto mmAB = new MatMatStruct_AB();
1353:     PetscCall(MatProductSymbolic_MPIAIJKokkos_AB(product, A, B, mmAB));
1354:     mm = pdata->mmAB = mmAB;
1355:   } else if (ptype == MATPRODUCT_AtB) {
1356:     auto mmAtB = new MatMatStruct_AtB();
1357:     PetscCall(MatProductSymbolic_MPIAIJKokkos_AtB(product, A, B, mmAtB));
1358:     mm = pdata->mmAtB = mmAtB;
1359:   } else if (ptype == MATPRODUCT_PtAP) { // C = BtAB, computed as Z = AB; C= BtZ
1360:     Mat Zd, Zo, Z;                       // Zd, Zo are owned by pdata->Z

1362:     auto mmAB = new MatMatStruct_AB();
1363:     PetscCall(MatProductSymbolic_MPIAIJKokkos_AB(product, A, B, mmAB)); // Z stored as mmAB->{Cd, Co}
1364:     PetscCall(MatCreateSeqAIJKokkosWithKokkosCsrMatrix(PETSC_COMM_SELF, mmAB->Cd, &Zd));
1365:     PetscCall(MatCreateSeqAIJKokkosWithKokkosCsrMatrix(PETSC_COMM_SELF, mmAB->Co, &Zo));
1366:     pdata->mmAB = mmAB;

1368:     m = A->rmap->n; // Z's layout
1369:     n = B->cmap->n;
1370:     M = A->rmap->N;
1371:     N = B->cmap->N;
1372:     PetscCall(MatCreateMPIAIJWithSeqAIJ(comm, M, N, Zd, Zo, mmAB->garray, &Z));

1374:     auto mmAtB = new MatMatStruct_AtB();
1375:     PetscCall(MatProductSymbolic_MPIAIJKokkos_AtB(product, B, Z, mmAtB)); // final result C stored as mmAtB->{Cd, Co}

1377:     pdata->Z = Z; // give ownership to pdata
1378:     mm = pdata->mmAtB = mmAtB;
1379:   }

1381:   PetscCall(MatCreateSeqAIJKokkosWithKokkosCsrMatrix(PETSC_COMM_SELF, mm->Cd, &Cd));
1382:   PetscCall(MatCreateSeqAIJKokkosWithKokkosCsrMatrix(PETSC_COMM_SELF, mm->Co, &Co));

1384:   mpiaij         = (Mat_MPIAIJ *)C->data;
1385:   mpiaij->A      = Cd;
1386:   mpiaij->B      = Co;
1387:   mpiaij->garray = mm->garray;

1389:   C->preallocated     = PETSC_TRUE;
1390:   C->nooffprocentries = PETSC_TRUE;
1391:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
1392:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
1393:   C->nooffprocentries = nooffprocentries;
1394:   PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));

1396:   /* set block sizes */
1397:   switch (ptype) {
1398:   case MATPRODUCT_PtAP:
1399:     if (B->cmap->bs > 1) PetscCall(MatSetBlockSizes(C, B->cmap->bs, B->cmap->bs));
1400:     break;
1401:   case MATPRODUCT_RARt:
1402:     if (B->rmap->bs > 1) PetscCall(MatSetBlockSizes(C, B->rmap->bs, B->rmap->bs));
1403:     break;
1404:   case MATPRODUCT_ABC:
1405:     PetscCall(MatSetBlockSizesFromMats(C, A, product->C));
1406:     break;
1407:   case MATPRODUCT_AB:
1408:     PetscCall(MatSetBlockSizesFromMats(C, A, B));
1409:     break;
1410:   case MATPRODUCT_AtB:
1411:     if (A->cmap->bs > 1 || B->cmap->bs > 1) PetscCall(MatSetBlockSizes(C, A->cmap->bs, B->cmap->bs));
1412:     break;
1413:   case MATPRODUCT_ABt:
1414:     if (A->rmap->bs > 1 || B->rmap->bs > 1) PetscCall(MatSetBlockSizes(C, A->rmap->bs, B->rmap->bs));
1415:     break;
1416:   default:
1417:     SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Not for ProductType %s", MatProductTypes[ptype]);
1418:   }
1419:   C->product->data       = pdata;
1420:   C->product->destroy    = MatProductCtxDestroy_MPIAIJKokkos;
1421:   C->ops->productnumeric = MatProductNumeric_MPIAIJKokkos;
1422:   PetscFunctionReturn(PETSC_SUCCESS);
1423: }

1425: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_MPIAIJKokkos(Mat mat)
1426: {
1427:   Mat_Product *product = mat->product;
1428:   PetscBool    match   = PETSC_FALSE; // Do we multiply two MPIAIJKokkos matrices?
1429:   PetscBool    usecpu  = PETSC_FALSE; // Use PETSc MATAIJ's native CPU implementation?

1431:   PetscFunctionBegin;
1432:   MatCheckProduct(mat, 1);
1433:   PetscCall(PetscObjectTypeCompare((PetscObject)product->B, ((PetscObject)product->A)->type_name, &match));
1434:   if (match) { /* we can always fallback to the CPU if requested */
1435:     switch (product->type) {
1436:     case MATPRODUCT_AB:
1437:       if (product->api_user) {
1438:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatMatMult", "Mat");
1439:         PetscCall(PetscOptionsBool("-matmatmult_backend_cpu", "Use CPU code", "MatMatMult", usecpu, &usecpu, NULL));
1440:         PetscOptionsEnd();
1441:       } else {
1442:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_AB", "Mat");
1443:         PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatMatMult", usecpu, &usecpu, NULL));
1444:         PetscOptionsEnd();
1445:       }
1446:       break;
1447:     case MATPRODUCT_AtB:
1448:       if (product->api_user) {
1449:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatTransposeMatMult", "Mat");
1450:         PetscCall(PetscOptionsBool("-mattransposematmult_backend_cpu", "Use CPU code", "MatTransposeMatMult", usecpu, &usecpu, NULL));
1451:         PetscOptionsEnd();
1452:       } else {
1453:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_AtB", "Mat");
1454:         PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatTransposeMatMult", usecpu, &usecpu, NULL));
1455:         PetscOptionsEnd();
1456:       }
1457:       break;
1458:     case MATPRODUCT_PtAP:
1459:       if (product->api_user) {
1460:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatPtAP", "Mat");
1461:         PetscCall(PetscOptionsBool("-matptap_backend_cpu", "Use CPU code", "MatPtAP", usecpu, &usecpu, NULL));
1462:         PetscOptionsEnd();
1463:       } else {
1464:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_PtAP", "Mat");
1465:         PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatPtAP", usecpu, &usecpu, NULL));
1466:         PetscOptionsEnd();
1467:       }
1468:       break;
1469:     default:
1470:       break;
1471:     }
1472:     match = (PetscBool)!usecpu;
1473:   }
1474:   if (match) {
1475:     switch (product->type) {
1476:     case MATPRODUCT_AB:
1477:     case MATPRODUCT_AtB:
1478:     case MATPRODUCT_PtAP:
1479:       mat->ops->productsymbolic = MatProductSymbolic_MPIAIJKokkos;
1480:       break;
1481:     default:
1482:       break;
1483:     }
1484:   }
1485:   /* fallback to MPIAIJ ops */
1486:   if (!mat->ops->productsymbolic) PetscCall(MatProductSetFromOptions_MPIAIJ(mat));
1487:   PetscFunctionReturn(PETSC_SUCCESS);
1488: }

1490: // Mirror of MatCOOStruct_MPIAIJ on device
1491: struct MatCOOStruct_MPIAIJKokkos {
1492:   PetscCount           n;
1493:   PetscSF              sf;
1494:   PetscCount           Annz, Bnnz;
1495:   PetscCount           Annz2, Bnnz2;
1496:   PetscCountKokkosView Ajmap1, Aperm1;
1497:   PetscCountKokkosView Bjmap1, Bperm1;
1498:   PetscCountKokkosView Aimap2, Ajmap2, Aperm2;
1499:   PetscCountKokkosView Bimap2, Bjmap2, Bperm2;
1500:   PetscCountKokkosView Cperm1;
1501:   MatScalarKokkosView  sendbuf, recvbuf;

1503:   MatCOOStruct_MPIAIJKokkos(const MatCOOStruct_MPIAIJ *coo_h)
1504:   {
1505:     auto exec = PetscGetKokkosExecutionSpace();

1507:     n       = coo_h->n;
1508:     sf      = coo_h->sf;
1509:     Annz    = coo_h->Annz;
1510:     Bnnz    = coo_h->Bnnz;
1511:     Annz2   = coo_h->Annz2;
1512:     Bnnz2   = coo_h->Bnnz2;
1513:     Ajmap1  = Kokkos::create_mirror_view_and_copy(exec, PetscCountKokkosViewHost(coo_h->Ajmap1, coo_h->Annz + 1));
1514:     Aperm1  = Kokkos::create_mirror_view_and_copy(exec, PetscCountKokkosViewHost(coo_h->Aperm1, coo_h->Atot1));
1515:     Bjmap1  = Kokkos::create_mirror_view_and_copy(exec, PetscCountKokkosViewHost(coo_h->Bjmap1, coo_h->Bnnz + 1));
1516:     Bperm1  = Kokkos::create_mirror_view_and_copy(exec, PetscCountKokkosViewHost(coo_h->Bperm1, coo_h->Btot1));
1517:     Aimap2  = Kokkos::create_mirror_view_and_copy(exec, PetscCountKokkosViewHost(coo_h->Aimap2, coo_h->Annz2));
1518:     Ajmap2  = Kokkos::create_mirror_view_and_copy(exec, PetscCountKokkosViewHost(coo_h->Ajmap2, coo_h->Annz2 + 1));
1519:     Aperm2  = Kokkos::create_mirror_view_and_copy(exec, PetscCountKokkosViewHost(coo_h->Aperm2, coo_h->Atot2));
1520:     Bimap2  = Kokkos::create_mirror_view_and_copy(exec, PetscCountKokkosViewHost(coo_h->Bimap2, coo_h->Bnnz2));
1521:     Bjmap2  = Kokkos::create_mirror_view_and_copy(exec, PetscCountKokkosViewHost(coo_h->Bjmap2, coo_h->Bnnz2 + 1));
1522:     Bperm2  = Kokkos::create_mirror_view_and_copy(exec, PetscCountKokkosViewHost(coo_h->Bperm2, coo_h->Btot2));
1523:     Cperm1  = Kokkos::create_mirror_view_and_copy(exec, PetscCountKokkosViewHost(coo_h->Cperm1, coo_h->sendlen));
1524:     sendbuf = Kokkos::create_mirror_view(Kokkos::WithoutInitializing, exec, MatScalarKokkosViewHost(coo_h->sendbuf, coo_h->sendlen));
1525:     recvbuf = Kokkos::create_mirror_view(Kokkos::WithoutInitializing, exec, MatScalarKokkosViewHost(coo_h->recvbuf, coo_h->recvlen));
1526:     PetscCallVoid(PetscObjectReference((PetscObject)sf));
1527:   }

1529:   ~MatCOOStruct_MPIAIJKokkos() { PetscCallVoid(PetscSFDestroy(&sf)); }
1530: };

1532: static PetscErrorCode MatCOOStructDestroy_MPIAIJKokkos(PetscCtxRt data)
1533: {
1534:   PetscFunctionBegin;
1535:   PetscCallCXX(delete *static_cast<MatCOOStruct_MPIAIJKokkos **>(data));
1536:   PetscFunctionReturn(PETSC_SUCCESS);
1537: }

1539: static PetscErrorCode MatSetPreallocationCOO_MPIAIJKokkos(Mat mat, PetscCount coo_n, PetscInt coo_i[], PetscInt coo_j[])
1540: {
1541:   PetscContainer             container_h, container_d;
1542:   MatCOOStruct_MPIAIJ       *coo_h;
1543:   MatCOOStruct_MPIAIJKokkos *coo_d;

1545:   PetscFunctionBegin;
1546:   PetscCall(MatSetPreallocationCOO_MPIAIJ(mat, coo_n, coo_i, coo_j)); /* mpiaij->A,B's type is set to seqaijkokkos */
1547:   mat->preallocated = PETSC_TRUE;
1548:   PetscCall(MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY));
1549:   PetscCall(MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY));
1550:   PetscCall(MatZeroEntries(mat));

1552:   // Copy the COO struct to device
1553:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", (PetscObject *)&container_h));
1554:   PetscCall(PetscContainerGetPointer(container_h, &coo_h));
1555:   PetscCallCXX(coo_d = new MatCOOStruct_MPIAIJKokkos(coo_h));

1557:   // Put the COO struct in a container and then attach that to the matrix
1558:   PetscCall(PetscContainerCreate(PETSC_COMM_SELF, &container_d));
1559:   PetscCall(PetscContainerSetPointer(container_d, coo_d));
1560:   PetscCall(PetscContainerSetCtxDestroy(container_d, MatCOOStructDestroy_MPIAIJKokkos));
1561:   PetscCall(PetscObjectCompose((PetscObject)mat, "__PETSc_MatCOOStruct_Device", (PetscObject)container_d));
1562:   PetscCall(PetscContainerDestroy(&container_d));
1563:   PetscFunctionReturn(PETSC_SUCCESS);
1564: }

1566: static PetscErrorCode MatSetValuesCOO_MPIAIJKokkos(Mat mat, const PetscScalar v[], InsertMode imode)
1567: {
1568:   Mat_MPIAIJ                   *mpiaij = static_cast<Mat_MPIAIJ *>(mat->data);
1569:   Mat                           A = mpiaij->A, B = mpiaij->B;
1570:   Kokkos::View<PetscScalar *>   Aa, Ba;
1571:   MatScalarKokkosView           v1;
1572:   PetscMemType                  memtype;
1573:   PetscContainer                container;
1574:   MatCOOStruct_MPIAIJKokkos    *coo;
1575:   Kokkos::DefaultExecutionSpace exec = PetscGetKokkosExecutionSpace();

1577:   PetscFunctionBegin;
1578:   PetscCall(MatMPIAIJCheckCOONonzeroState(mat));
1579:   PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Device", (PetscObject *)&container));
1580:   PetscCall(PetscContainerGetPointer(container, &coo));

1582:   const auto &n      = coo->n;
1583:   const auto &Annz   = coo->Annz;
1584:   const auto &Annz2  = coo->Annz2;
1585:   const auto &Bnnz   = coo->Bnnz;
1586:   const auto &Bnnz2  = coo->Bnnz2;
1587:   const auto &vsend  = coo->sendbuf;
1588:   const auto &v2     = coo->recvbuf;
1589:   const auto &Ajmap1 = coo->Ajmap1;
1590:   const auto &Ajmap2 = coo->Ajmap2;
1591:   const auto &Aimap2 = coo->Aimap2;
1592:   const auto &Bjmap1 = coo->Bjmap1;
1593:   const auto &Bjmap2 = coo->Bjmap2;
1594:   const auto &Bimap2 = coo->Bimap2;
1595:   const auto &Aperm1 = coo->Aperm1;
1596:   const auto &Aperm2 = coo->Aperm2;
1597:   const auto &Bperm1 = coo->Bperm1;
1598:   const auto &Bperm2 = coo->Bperm2;
1599:   const auto &Cperm1 = coo->Cperm1;

1601:   PetscCall(PetscGetMemType(v, &memtype)); /* Return PETSC_MEMTYPE_HOST when v is NULL */
1602:   if (PetscMemTypeHost(memtype)) {         /* If user gave v[] in host, we need to copy it to device if any */
1603:     v1 = Kokkos::create_mirror_view_and_copy(exec, MatScalarKokkosViewHost((PetscScalar *)v, n));
1604:     PetscCall(PetscLogCpuToGpu(n * sizeof(PetscScalar)));
1605:   } else {
1606:     v1 = MatScalarKokkosView((PetscScalar *)v, n); /* Directly use v[]'s memory */
1607:   }

1609:   if (imode == INSERT_VALUES) {
1610:     PetscCall(MatSeqAIJGetKokkosViewWrite(A, &Aa)); /* write matrix values */
1611:     PetscCall(MatSeqAIJGetKokkosViewWrite(B, &Ba));
1612:   } else {
1613:     PetscCall(MatSeqAIJGetKokkosView(A, &Aa)); /* read & write matrix values */
1614:     PetscCall(MatSeqAIJGetKokkosView(B, &Ba));
1615:   }

1617:   PetscCall(PetscLogGpuTimeBegin());
1618:   /* Pack entries to be sent to remote */
1619:   Kokkos::parallel_for(Kokkos::RangePolicy<>(exec, 0, vsend.extent(0)), KOKKOS_LAMBDA(const PetscCount i) { vsend(i) = v1(Cperm1(i)); });

1621:   /* Send remote entries to their owner and overlap the communication with local computation */
1622:   PetscCall(PetscSFSynchronizeKokkos_Private(coo->sf, PETSC_TRUE));
1623:   PetscCall(PetscSFReduceWithMemTypeBegin(coo->sf, MPIU_SCALAR, PETSC_MEMTYPE_KOKKOS, vsend.data(), PETSC_MEMTYPE_KOKKOS, v2.data(), MPI_REPLACE));
1624:   /* Add local entries to A and B in one kernel */
1625:   Kokkos::parallel_for(
1626:     Kokkos::RangePolicy<>(exec, 0, Annz + Bnnz), KOKKOS_LAMBDA(PetscCount i) {
1627:       PetscScalar sum = 0.0;
1628:       if (i < Annz) {
1629:         for (PetscCount k = Ajmap1(i); k < Ajmap1(i + 1); k++) sum += v1(Aperm1(k));
1630:         Aa(i) = (imode == INSERT_VALUES ? 0.0 : Aa(i)) + sum;
1631:       } else {
1632:         i -= Annz;
1633:         for (PetscCount k = Bjmap1(i); k < Bjmap1(i + 1); k++) sum += v1(Bperm1(k));
1634:         Ba(i) = (imode == INSERT_VALUES ? 0.0 : Ba(i)) + sum;
1635:       }
1636:     });
1637:   PetscCall(PetscSFReduceEnd(coo->sf, MPIU_SCALAR, vsend.data(), v2.data(), MPI_REPLACE));
1638:   PetscCall(PetscSFSynchronizeKokkos_Private(coo->sf, PETSC_FALSE));

1640:   /* Add received remote entries to A and B in one kernel */
1641:   Kokkos::parallel_for(
1642:     Kokkos::RangePolicy<>(exec, 0, Annz2 + Bnnz2), KOKKOS_LAMBDA(PetscCount i) {
1643:       if (i < Annz2) {
1644:         for (PetscCount k = Ajmap2(i); k < Ajmap2(i + 1); k++) Aa(Aimap2(i)) += v2(Aperm2(k));
1645:       } else {
1646:         i -= Annz2;
1647:         for (PetscCount k = Bjmap2(i); k < Bjmap2(i + 1); k++) Ba(Bimap2(i)) += v2(Bperm2(k));
1648:       }
1649:     });
1650:   PetscCall(PetscLogGpuTimeEnd());

1652:   if (imode == INSERT_VALUES) {
1653:     PetscCall(MatSeqAIJRestoreKokkosViewWrite(A, &Aa)); /* Increase A & B's state etc. */
1654:     PetscCall(MatSeqAIJRestoreKokkosViewWrite(B, &Ba));
1655:   } else {
1656:     PetscCall(MatSeqAIJRestoreKokkosView(A, &Aa));
1657:     PetscCall(MatSeqAIJRestoreKokkosView(B, &Ba));
1658:   }
1659:   PetscFunctionReturn(PETSC_SUCCESS);
1660: }

1662: static PetscErrorCode MatDestroy_MPIAIJKokkos(Mat A)
1663: {
1664:   PetscFunctionBegin;
1665:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatMPIAIJSetPreallocation_C", NULL));
1666:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatMPIAIJGetLocalMatMerge_C", NULL));
1667:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSetPreallocationCOO_C", NULL));
1668:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSetValuesCOO_C", NULL));
1669:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_mpiaijkokkos_mpidense_C", NULL));
1670: #if PetscDefined(HAVE_CUDA)
1671:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_mpiaijkokkos_mpidensecuda_C", NULL));
1672: #endif
1673: #if PetscDefined(HAVE_HIP)
1674:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_mpiaijkokkos_mpidensehip_C", NULL));
1675: #endif
1676: #if PetscDefined(HAVE_HYPRE)
1677:   PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatConvert_mpiaijkokkos_hypre_C", NULL));
1678: #endif
1679:   PetscCall(MatDestroy_MPIAIJ(A));
1680:   PetscFunctionReturn(PETSC_SUCCESS);
1681: }

1683: static PetscErrorCode MatShift_MPIAIJKokkos(Mat A, PetscScalar a)
1684: {
1685:   Mat_MPIAIJ *mpiaij = static_cast<Mat_MPIAIJ *>(A->data);
1686:   PetscBool   congruent;

1688:   PetscFunctionBegin;
1689:   PetscCall(MatHasCongruentLayouts(A, &congruent));
1690:   if (congruent) { // square matrix and the diagonals are solely in the diag block
1691:     PetscCall(MatShift(mpiaij->A, a));
1692:   } else { // too hard, use the general version
1693:     PetscCall(MatShift_Basic(A, a));
1694:   }
1695:   PetscFunctionReturn(PETSC_SUCCESS);
1696: }

1698: static PetscErrorCode MatNorm_MPIAIJKokkos(Mat mat, NormType type, PetscReal *norm)
1699: {
1700:   Mat_MPIAIJ *aij = static_cast<Mat_MPIAIJ *>(mat->data);
1701:   PetscInt    nz  = static_cast<Mat_SeqAIJ *>(aij->A->data)->nz + static_cast<Mat_SeqAIJ *>(aij->B->data)->nz;
1702:   MPI_Comm    comm;

1704:   PetscFunctionBegin;
1705:   if (aij->size == 1) {
1706:     PetscCall(MatNorm(aij->A, type, norm));
1707:     PetscFunctionReturn(PETSC_SUCCESS);
1708:   }
1709:   PetscCall(PetscObjectGetComm((PetscObject)mat, &comm));
1710:   if (type == NORM_FROBENIUS) {
1711:     PetscReal sumA, sumB;

1713:     PetscCall(PetscLogGpuTimeBegin());
1714:     PetscCall(MatSeqAIJKokkosGetFrobeniusSquared_Private(aij->A, &sumA));
1715:     PetscCall(MatSeqAIJKokkosGetFrobeniusSquared_Private(aij->B, &sumB));
1716:     PetscCall(PetscLogGpuTimeEnd());
1717:     *norm = sumA + sumB;
1718:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, norm, 1, MPIU_REAL, MPIU_SUM, comm));
1719:     *norm = PetscSqrtReal(*norm);
1720:     PetscCall(PetscLogGpuFlops(2.0 * nz));
1721:   } else if (type == NORM_1) { // max column sum; as in MatMultTranspose(), a reverse scatter adds B's column sums to the owning ranks
1722:     Vec                   col;
1723:     PetscScalarKokkosView colv, lv;

1725:     PetscCall(MatCreateVecs(mat, &col, NULL));
1726:     PetscCall(PetscLogGpuTimeBegin());
1727:     PetscCall(VecGetKokkosViewWrite(col, &colv));
1728:     PetscCall(MatSeqAIJKokkosGetColumnAbsSums_Private(aij->A, colv));
1729:     PetscCall(VecRestoreKokkosViewWrite(col, &colv));
1730:     PetscCall(VecGetKokkosViewWrite(aij->lvec, &lv));
1731:     PetscCall(MatSeqAIJKokkosGetColumnAbsSums_Private(aij->B, lv));
1732:     PetscCall(VecRestoreKokkosViewWrite(aij->lvec, &lv));
1733:     PetscCall(PetscLogGpuTimeEnd());
1734:     PetscCall(VecScatterBegin(aij->Mvctx, aij->lvec, col, ADD_VALUES, SCATTER_REVERSE));
1735:     PetscCall(VecScatterEnd(aij->Mvctx, aij->lvec, col, ADD_VALUES, SCATTER_REVERSE));
1736:     PetscCall(VecNorm(col, NORM_INFINITY, norm));
1737:     PetscCall(VecDestroy(&col));
1738:     PetscCall(PetscLogGpuFlops(nz));
1739:   } else if (type == NORM_INFINITY) { // max row sum, where a row spans both A and B
1740:     PetscCall(PetscLogGpuTimeBegin());
1741:     PetscCall(MatSeqAIJKokkosGetMaxRowAbsSum_Private(aij->A, aij->B, norm));
1742:     PetscCall(PetscLogGpuTimeEnd());
1743:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, norm, 1, MPIU_REAL, MPIU_MAX, comm));
1744:     PetscCall(PetscLogGpuFlops(PetscMax(nz - 1, 0)));
1745:   } else SETERRQ(comm, PETSC_ERR_SUP, "No support for two norm");
1746:   PetscFunctionReturn(PETSC_SUCCESS);
1747: }

1749: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_MPIAIJ_MPIDense(Mat);

1751: static PetscErrorCode MatSetOps_MPIAIJKokkos(Mat B)
1752: {
1753:   PetscFunctionBegin;
1754:   B->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.
1755:   B->ops->assemblyend           = MatAssemblyEnd_MPIAIJKokkos;
1756:   B->ops->mult                  = MatMult_MPIAIJKokkos;
1757:   B->ops->multadd               = MatMultAdd_MPIAIJKokkos;
1758:   B->ops->multtranspose         = MatMultTranspose_MPIAIJKokkos;
1759:   B->ops->productsetfromoptions = MatProductSetFromOptions_MPIAIJKokkos;
1760:   B->ops->destroy               = MatDestroy_MPIAIJKokkos;
1761:   B->ops->shift                 = MatShift_MPIAIJKokkos;
1762:   B->ops->norm                  = MatNorm_MPIAIJKokkos;
1763:   B->ops->getrowsumabs          = MatGetRowSumAbs_AIJKokkos;
1764:   B->ops->getcurrentmemtype     = MatGetCurrentMemType_MPIAIJ;
1765:   B->ops->bindtocpu             = MatBindToCPU_SeqAIJKokkos;

1767:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMPIAIJSetPreallocation_C", MatMPIAIJSetPreallocation_MPIAIJKokkos));
1768:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatMPIAIJGetLocalMatMerge_C", MatMPIAIJGetLocalMatMerge_MPIAIJKokkos));
1769:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSetPreallocationCOO_C", MatSetPreallocationCOO_MPIAIJKokkos));
1770:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatSetValuesCOO_C", MatSetValuesCOO_MPIAIJKokkos));
1771:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_mpiaijkokkos_mpidense_C", MatProductSetFromOptions_MPIAIJ_MPIDense));
1772: #if PetscDefined(HAVE_CUDA)
1773:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_mpiaijkokkos_mpidensecuda_C", MatProductSetFromOptions_MPIAIJ_MPIDense));
1774: #endif
1775: #if PetscDefined(HAVE_HIP)
1776:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatProductSetFromOptions_mpiaijkokkos_mpidensehip_C", MatProductSetFromOptions_MPIAIJ_MPIDense));
1777: #endif
1778: #if PetscDefined(HAVE_HYPRE)
1779:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_mpiaijkokkos_hypre_C", MatConvert_AIJ_HYPRE));
1780: #endif
1781:   PetscFunctionReturn(PETSC_SUCCESS);
1782: }

1784: PETSC_INTERN PetscErrorCode MatConvert_MPIAIJ_MPIAIJKokkos(Mat A, MatType, MatReuse reuse, Mat *newmat)
1785: {
1786:   Mat         B;
1787:   Mat_MPIAIJ *b;

1789:   PetscFunctionBegin;
1790:   if (reuse == MAT_INITIAL_MATRIX) {
1791:     PetscCall(MatDuplicate(A, MAT_COPY_VALUES, newmat));
1792:   } else if (reuse == MAT_REUSE_MATRIX) {
1793:     PetscCall(MatCopy(A, *newmat, SAME_NONZERO_PATTERN));
1794:   }
1795:   B = *newmat;

1797:   PetscCall(PetscFree(B->defaultvectype));
1798:   PetscCall(PetscStrallocpy(VECKOKKOS, &B->defaultvectype));
1799:   PetscCall(PetscObjectChangeTypeName((PetscObject)B, MATMPIAIJKOKKOS));

1801:   b = static_cast<Mat_MPIAIJ *>(B->data);
1802:   if (b->A) PetscCall(MatSetType(b->A, MATSEQAIJKOKKOS));
1803:   if (b->B) PetscCall(MatSetType(b->B, MATSEQAIJKOKKOS));
1804:   if (b->lvec) PetscCall(VecSetType(b->lvec, VECSEQKOKKOS));
1805:   PetscCall(MatSetOps_MPIAIJKokkos(B));
1806:   PetscFunctionReturn(PETSC_SUCCESS);
1807: }

1809: /*MC
1810:    MATAIJKOKKOS - "mpiaijkokkos", a matrix type to be used for CSR sparse matrices with Kokkos.

1812:    A matrix type using Kokkos-Kernels CrsMatrix type for portability across different device types

1814:    Options Database Key:
1815: .  -mat_type aijkokkos - sets the matrix type to `MATAIJKOKKOS`

1817:   Level: beginner

1819: .seealso: [](ch_matrices), `Mat`, `MatCreateAIJKokkos()`, `MATSEQAIJKOKKOS`, `MATSEQAIJ`, `MATMPIAIJ`
1820: M*/
1821: PETSC_EXTERN PetscErrorCode MatCreate_MPIAIJKokkos(Mat A)
1822: {
1823:   PetscFunctionBegin;
1824:   PetscCall(PetscKokkosInitializeCheck());
1825:   PetscCall(MatCreate_MPIAIJ(A));
1826:   PetscCall(MatConvert_MPIAIJ_MPIAIJKokkos(A, MATMPIAIJKOKKOS, MAT_INPLACE_MATRIX, &A));
1827:   PetscFunctionReturn(PETSC_SUCCESS);
1828: }

1830: /*@
1831:   MatCreateAIJKokkos - Creates a sparse matrix in `MATAIJKOKKOS` (compressed row) format
1832:   (the default parallel PETSc format).  This matrix will ultimately pushed down
1833:   to Kokkos for calculations.

1835:   Collective

1837:   Input Parameters:
1838: + comm  - MPI communicator, set to `PETSC_COMM_SELF`
1839: . m     - number of local rows (or `PETSC_DECIDE` to have calculated if `M` is given)
1840:            This value should be the same as the local size used in creating the
1841:            y vector for the matrix-vector product y = Ax.
1842: . n     - This value should be the same as the local size used in creating the
1843:        x vector for the matrix-vector product y = Ax. (or `PETSC_DECIDE` to have
1844:        calculated if N is given) For square matrices n is almost always `m`.
1845: . M     - number of global rows (or `PETSC_DETERMINE` to have calculated if `m` is given)
1846: . N     - number of global columns (or `PETSC_DETERMINE` to have calculated if `n` is given)
1847: . d_nz  - number of nonzeros per row in DIAGONAL portion of local submatrix
1848:            (same value is used for all local rows)
1849: . d_nnz - array containing the number of nonzeros in the various rows of the
1850:            DIAGONAL portion of the local submatrix (possibly different for each row)
1851:            or `NULL`, if `d_nz` is used to specify the nonzero structure.
1852:            The size of this array is equal to the number of local rows, i.e `m`.
1853:            For matrices you plan to factor you must leave room for the diagonal entry and
1854:            put in the entry even if it is zero.
1855: . o_nz  - number of nonzeros per row in the OFF-DIAGONAL portion of local
1856:            submatrix (same value is used for all local rows).
1857: - o_nnz - array containing the number of nonzeros in the various rows of the
1858:            OFF-DIAGONAL portion of the local submatrix (possibly different for
1859:            each row) or `NULL`, if `o_nz` is used to specify the nonzero
1860:            structure. The size of this array is equal to the number
1861:            of local rows, i.e `m`.

1863:   Output Parameter:
1864: . A - the matrix

1866:   Level: intermediate

1868:   Notes:
1869:   It is recommended that one use the `MatCreate()`, `MatSetType()` and/or `MatSetFromOptions()`,
1870:   MatXXXXSetPreallocation() paradigm instead of this routine directly.
1871:   [MatXXXXSetPreallocation() is, for example, `MatSeqAIJSetPreallocation()`]

1873:   The AIJ format, also called compressed row storage), is fully compatible with standard Fortran
1874:   storage.  That is, the stored row and column indices can begin at
1875:   either one (as in Fortran) or zero.

1877: .seealso: [](ch_matrices), `Mat`, `MATAIJKOKKOS`, `MATSEQAIJKOKKOS`, `MATMPIAIJKOKKOS`, `MatCreate()`, `MatCreateAIJ()`, `MatSetValues()`,
1878:           `MatSeqAIJSetColumnIndices()`, `MatCreateSeqAIJWithArrays()`
1879: @*/
1880: PetscErrorCode MatCreateAIJKokkos(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt M, PetscInt N, PetscInt d_nz, const PetscInt d_nnz[], PetscInt o_nz, const PetscInt o_nnz[], Mat *A)
1881: {
1882:   PetscMPIInt size;

1884:   PetscFunctionBegin;
1885:   PetscCall(MatCreate(comm, A));
1886:   PetscCall(MatSetSizes(*A, m, n, M, N));
1887:   PetscCallMPI(MPI_Comm_size(comm, &size));
1888:   if (size > 1) {
1889:     PetscCall(MatSetType(*A, MATMPIAIJKOKKOS));
1890:     PetscCall(MatMPIAIJSetPreallocation(*A, d_nz, d_nnz, o_nz, o_nnz));
1891:   } else {
1892:     PetscCall(MatSetType(*A, MATSEQAIJKOKKOS));
1893:     PetscCall(MatSeqAIJSetPreallocation(*A, d_nz, d_nnz));
1894:   }
1895:   PetscFunctionReturn(PETSC_SUCCESS);
1896: }