Actual source code: mpimatmatmult.c

  1: /*
  2:   Defines matrix-matrix product routines for pairs of MPIAIJ matrices
  3:           C = A * B
  4: */
  5: #include <../src/mat/impls/aij/seq/aij.h>
  6: #include <../src/mat/utils/freespace.h>
  7: #include <../src/mat/impls/aij/mpi/mpiaij.h>
  8: #include <../src/mat/impls/dense/mpi/mpidense.h>
  9: #include <petsc/private/vecimpl.h>
 10: #include <petsc/private/sfimpl.h>

 12: #if PetscDefined(HAVE_HYPRE)
 13: PETSC_INTERN PetscErrorCode MatMatMultSymbolic_AIJ_AIJ_wHYPRE(Mat, Mat, PetscReal, Mat);
 14: #endif

 16: PETSC_INTERN PetscErrorCode MatProductSymbolic_ABt_MPIAIJ_MPIAIJ(Mat C)
 17: {
 18:   Mat_Product *product = C->product;
 19:   Mat          B       = product->B;

 21:   PetscFunctionBegin;
 22:   PetscCall(MatTranspose(B, MAT_INITIAL_MATRIX, &product->B));
 23:   PetscCall(MatDestroy(&B));
 24:   PetscCall(MatProductSymbolic_AB_MPIAIJ_MPIAIJ(C));
 25:   PetscFunctionReturn(PETSC_SUCCESS);
 26: }

 28: PETSC_INTERN PetscErrorCode MatProductSymbolic_AB_MPIAIJ_MPIAIJ(Mat C)
 29: {
 30:   Mat_Product        *product = C->product;
 31:   Mat                 A = product->A, B = product->B;
 32:   MatProductAlgorithm alg  = product->alg;
 33:   PetscReal           fill = product->fill;
 34:   PetscBool           flg;

 36:   PetscFunctionBegin;
 37:   /* scalable */
 38:   PetscCall(PetscStrcmp(alg, "scalable", &flg));
 39:   if (flg || C->structure_only) {
 40:     if (C->structure_only) PetscCall(MatProductSetAlgorithm(C, "scalable"));
 41:     PetscCall(MatMatMultSymbolic_MPIAIJ_MPIAIJ(A, B, fill, C));
 42:     PetscFunctionReturn(PETSC_SUCCESS);
 43:   }

 45:   /* nonscalable */
 46:   PetscCall(PetscStrcmp(alg, "nonscalable", &flg));
 47:   if (flg) {
 48:     PetscCall(MatMatMultSymbolic_MPIAIJ_MPIAIJ_nonscalable(A, B, fill, C));
 49:     PetscFunctionReturn(PETSC_SUCCESS);
 50:   }

 52:   /* seqmpi */
 53:   PetscCall(PetscStrcmp(alg, "seqmpi", &flg));
 54:   if (flg) {
 55:     PetscCall(MatMatMultSymbolic_MPIAIJ_MPIAIJ_seqMPI(A, B, fill, C));
 56:     PetscFunctionReturn(PETSC_SUCCESS);
 57:   }

 59:   /* backend general code */
 60:   PetscCall(PetscStrcmp(alg, "backend", &flg));
 61:   if (flg) {
 62:     PetscCall(MatProductSymbolic_MPIAIJBACKEND(C));
 63:     PetscFunctionReturn(PETSC_SUCCESS);
 64:   }

 66: #if PetscDefined(HAVE_HYPRE)
 67:   PetscCall(PetscStrcmp(alg, "hypre", &flg));
 68:   if (flg) {
 69:     PetscCall(MatMatMultSymbolic_AIJ_AIJ_wHYPRE(A, B, fill, C));
 70:     PetscFunctionReturn(PETSC_SUCCESS);
 71:   }
 72: #endif
 73:   SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_SUP, "Mat Product Algorithm is not supported");
 74: }

 76: PetscErrorCode MatProductCtxDestroy_MPIAIJ_MatMatMult(PetscCtxRt data)
 77: {
 78:   MatProductCtx_APMPI *ptap = *(MatProductCtx_APMPI **)data;

 80:   PetscFunctionBegin;
 81:   PetscCall(PetscFree2(ptap->startsj_s, ptap->startsj_r));
 82:   PetscCall(PetscFree(ptap->bufa));
 83:   PetscCall(MatDestroy(&ptap->P_loc));
 84:   PetscCall(MatDestroy(&ptap->P_oth));
 85:   PetscCall(MatDestroy(&ptap->Pt));
 86:   PetscCall(PetscFree(ptap->api));
 87:   PetscCall(PetscFree(ptap->apj));
 88:   PetscCall(PetscFree(ptap->apa));
 89:   PetscCall(PetscFree(ptap));
 90:   PetscFunctionReturn(PETSC_SUCCESS);
 91: }

 93: PetscErrorCode MatMatMultNumeric_MPIAIJ_MPIAIJ_nonscalable(Mat A, Mat P, Mat C)
 94: {
 95:   Mat_MPIAIJ          *a = (Mat_MPIAIJ *)A->data, *c = (Mat_MPIAIJ *)C->data;
 96:   Mat_SeqAIJ          *ad = (Mat_SeqAIJ *)a->A->data, *ao = (Mat_SeqAIJ *)a->B->data;
 97:   Mat_SeqAIJ          *cd = (Mat_SeqAIJ *)c->A->data, *co = (Mat_SeqAIJ *)c->B->data;
 98:   PetscScalar         *cda, *coa;
 99:   Mat_SeqAIJ          *p_loc, *p_oth;
100:   PetscScalar         *apa, *ca;
101:   PetscInt             cm = C->rmap->n;
102:   MatProductCtx_APMPI *ptap;
103:   PetscInt            *api, *apj, *apJ, i, k;
104:   PetscInt             cstart = C->cmap->rstart;
105:   PetscInt             cdnz, conz, k0, k1;
106:   const PetscScalar   *dummy1, *dummy2, *dummy3, *dummy4;
107:   MPI_Comm             comm;
108:   PetscMPIInt          size;
109:   const PetscBool      nooffprocentries = C->nooffprocentries;

111:   PetscFunctionBegin;
112:   MatCheckProduct(C, 3);
113:   ptap = (MatProductCtx_APMPI *)C->product->data;
114:   PetscCheck(ptap, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtAP cannot be computed. Missing data");
115:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
116:   PetscCallMPI(MPI_Comm_size(comm, &size));
117:   PetscCheck(ptap->P_oth || size <= 1, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "AP cannot be reused. Do not call MatProductClear()");

119:   /* flag CPU mask for C */
120: #if PetscDefined(HAVE_DEVICE)
121:   if (C->offloadmask != PETSC_OFFLOAD_UNALLOCATED) C->offloadmask = PETSC_OFFLOAD_CPU;
122:   if (c->A->offloadmask != PETSC_OFFLOAD_UNALLOCATED) c->A->offloadmask = PETSC_OFFLOAD_CPU;
123:   if (c->B->offloadmask != PETSC_OFFLOAD_UNALLOCATED) c->B->offloadmask = PETSC_OFFLOAD_CPU;
124: #endif

126:   /* 1) get P_oth = ptap->P_oth  and P_loc = ptap->P_loc */
127:   /* update numerical values of P_oth and P_loc */
128:   PetscCall(MatGetBrowsOfAoCols_MPIAIJ(A, P, MAT_REUSE_MATRIX, &ptap->startsj_s, &ptap->startsj_r, &ptap->bufa, &ptap->P_oth));
129:   PetscCall(MatMPIAIJGetLocalMat(P, MAT_REUSE_MATRIX, &ptap->P_loc));

131:   /* 2) compute numeric C_loc = A_loc*P = Ad*P_loc + Ao*P_oth */
132:   /* get data from symbolic products */
133:   p_loc = (Mat_SeqAIJ *)ptap->P_loc->data;
134:   p_oth = NULL;
135:   if (size > 1) p_oth = (Mat_SeqAIJ *)ptap->P_oth->data;

137:   /* get apa for storing dense row A[i,:]*P */
138:   apa = ptap->apa;

140:   api = ptap->api;
141:   apj = ptap->apj;
142:   /* trigger copy to CPU */
143:   PetscCall(MatSeqAIJGetArrayRead(a->A, &dummy1));
144:   PetscCall(MatSeqAIJGetArrayRead(a->B, &dummy2));
145:   PetscCall(MatSeqAIJGetArrayRead(ptap->P_loc, &dummy3));
146:   if (ptap->P_oth) PetscCall(MatSeqAIJGetArrayRead(ptap->P_oth, &dummy4));
147:   PetscCall(MatSeqAIJGetArrayWrite(c->A, &cda));
148:   PetscCall(MatSeqAIJGetArrayWrite(c->B, &coa));
149:   for (i = 0; i < cm; i++) {
150:     /* compute apa = A[i,:]*P */
151:     AProw_nonscalable(i, ad, ao, p_loc, p_oth, apa);

153:     /* set values in C */
154:     apJ  = PetscSafePointerPlusOffset(apj, api[i]);
155:     cdnz = cd->i[i + 1] - cd->i[i];
156:     conz = co->i[i + 1] - co->i[i];

158:     /* 1st off-diagonal part of C */
159:     ca = PetscSafePointerPlusOffset(coa, co->i[i]);
160:     k  = 0;
161:     for (k0 = 0; k0 < conz; k0++) {
162:       if (apJ[k] >= cstart) break;
163:       ca[k0]        = apa[apJ[k]];
164:       apa[apJ[k++]] = 0.0;
165:     }

167:     /* diagonal part of C */
168:     ca = PetscSafePointerPlusOffset(cda, cd->i[i]);
169:     for (k1 = 0; k1 < cdnz; k1++) {
170:       ca[k1]        = apa[apJ[k]];
171:       apa[apJ[k++]] = 0.0;
172:     }

174:     /* 2nd off-diagonal part of C */
175:     ca = PetscSafePointerPlusOffset(coa, co->i[i]);
176:     for (; k0 < conz; k0++) {
177:       ca[k0]        = apa[apJ[k]];
178:       apa[apJ[k++]] = 0.0;
179:     }
180:   }
181:   PetscCall(MatSeqAIJRestoreArrayRead(a->A, &dummy1));
182:   PetscCall(MatSeqAIJRestoreArrayRead(a->B, &dummy2));
183:   PetscCall(MatSeqAIJRestoreArrayRead(ptap->P_loc, &dummy3));
184:   if (ptap->P_oth) PetscCall(MatSeqAIJRestoreArrayRead(ptap->P_oth, &dummy4));
185:   PetscCall(MatSeqAIJRestoreArrayWrite(c->A, &cda));
186:   PetscCall(MatSeqAIJRestoreArrayWrite(c->B, &coa));

188:   C->nooffprocentries = PETSC_TRUE;
189:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
190:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
191:   C->nooffprocentries = nooffprocentries;
192:   PetscFunctionReturn(PETSC_SUCCESS);
193: }

195: PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIAIJ_nonscalable(Mat A, Mat P, PetscReal fill, Mat C)
196: {
197:   MPI_Comm             comm;
198:   PetscMPIInt          size;
199:   MatProductCtx_APMPI *ptap;
200:   PetscFreeSpaceList   free_space = NULL, current_space = NULL;
201:   Mat_MPIAIJ          *a  = (Mat_MPIAIJ *)A->data;
202:   Mat_SeqAIJ          *ad = (Mat_SeqAIJ *)a->A->data, *ao = (Mat_SeqAIJ *)a->B->data, *p_loc, *p_oth;
203:   PetscInt            *pi_loc, *pj_loc, *pi_oth, *pj_oth, *dnz, *onz;
204:   PetscInt            *adi = ad->i, *adj = ad->j, *aoi = ao->i, *aoj = ao->j, rstart = A->rmap->rstart;
205:   PetscInt            *lnk, i, pnz, row, *api, *apj, *Jptr, apnz, nspacedouble = 0, j, nzi;
206:   PetscInt             am = A->rmap->n, pN = P->cmap->N, pn = P->cmap->n, pm = P->rmap->n;
207:   PetscBT              lnkbt;
208:   PetscReal            afill;
209:   MatType              mtype;
210:   const PetscBool      nooffprocentries = C->nooffprocentries;

212:   PetscFunctionBegin;
213:   MatCheckProduct(C, 4);
214:   PetscCheck(!C->product->data, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Extra product struct not empty");
215:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
216:   PetscCallMPI(MPI_Comm_size(comm, &size));

218:   /* create struct MatProductCtx_APMPI and attached it to C later */
219:   PetscCall(PetscNew(&ptap));

221:   /* get P_oth by taking rows of P (= non-zero cols of local A) from other processors */
222:   PetscCall(MatGetBrowsOfAoCols_MPIAIJ(A, P, MAT_INITIAL_MATRIX, &ptap->startsj_s, &ptap->startsj_r, &ptap->bufa, &ptap->P_oth));

224:   /* get P_loc by taking all local rows of P */
225:   PetscCall(MatMPIAIJGetLocalMat(P, MAT_INITIAL_MATRIX, &ptap->P_loc));

227:   p_loc  = (Mat_SeqAIJ *)ptap->P_loc->data;
228:   pi_loc = p_loc->i;
229:   pj_loc = p_loc->j;
230:   if (size > 1) {
231:     p_oth  = (Mat_SeqAIJ *)ptap->P_oth->data;
232:     pi_oth = p_oth->i;
233:     pj_oth = p_oth->j;
234:   } else {
235:     p_oth  = NULL;
236:     pi_oth = NULL;
237:     pj_oth = NULL;
238:   }

240:   /* first, compute symbolic AP = A_loc*P = A_diag*P_loc + A_off*P_oth */
241:   PetscCall(PetscMalloc1(am + 1, &api));
242:   ptap->api = api;
243:   api[0]    = 0;

245:   /* create and initialize a linked list */
246:   PetscCall(PetscLLCondensedCreate(pN, pN, &lnk, &lnkbt));

248:   /* Initial FreeSpace size is fill*(nnz(A)+nnz(P)) */
249:   PetscCall(PetscFreeSpaceGet(PetscRealIntMultTruncate(fill, PetscIntSumTruncate(adi[am], PetscIntSumTruncate(aoi[am], pi_loc[pm]))), &free_space));
250:   current_space = free_space;

252:   MatPreallocateBegin(comm, am, pn, dnz, onz);
253:   for (i = 0; i < am; i++) {
254:     /* diagonal portion of A */
255:     nzi = adi[i + 1] - adi[i];
256:     for (j = 0; j < nzi; j++) {
257:       row  = *adj++;
258:       pnz  = pi_loc[row + 1] - pi_loc[row];
259:       Jptr = pj_loc + pi_loc[row];
260:       /* add non-zero cols of P into the sorted linked list lnk */
261:       PetscCall(PetscLLCondensedAddSorted(pnz, Jptr, lnk, lnkbt));
262:     }
263:     /* off-diagonal portion of A */
264:     nzi = aoi[i + 1] - aoi[i];
265:     for (j = 0; j < nzi; j++) {
266:       row  = *aoj++;
267:       pnz  = pi_oth[row + 1] - pi_oth[row];
268:       Jptr = pj_oth + pi_oth[row];
269:       PetscCall(PetscLLCondensedAddSorted(pnz, Jptr, lnk, lnkbt));
270:     }
271:     /* add possible missing diagonal entry */
272:     if (C->force_diagonals) {
273:       j = i + rstart; /* column index */
274:       PetscCall(PetscLLCondensedAddSorted(1, &j, lnk, lnkbt));
275:     }

277:     apnz       = lnk[0];
278:     api[i + 1] = api[i] + apnz;

280:     /* if free space is not available, double the total space in the list */
281:     if (current_space->local_remaining < apnz) {
282:       PetscCall(PetscFreeSpaceGet(PetscIntSumTruncate(apnz, current_space->total_array_size), &current_space));
283:       nspacedouble++;
284:     }

286:     /* Copy data into free space, then initialize lnk */
287:     PetscCall(PetscLLCondensedClean(pN, apnz, current_space->array, lnk, lnkbt));
288:     PetscCall(MatPreallocateSet(i + rstart, apnz, current_space->array, dnz, onz));

290:     current_space->array = PetscSafePointerPlusOffset(current_space->array, apnz);
291:     current_space->local_used += apnz;
292:     current_space->local_remaining -= apnz;
293:   }

295:   /* Allocate space for apj, initialize apj, and */
296:   /* destroy list of free space and other temporary array(s) */
297:   PetscCall(PetscMalloc1(api[am], &ptap->apj));
298:   apj = ptap->apj;
299:   PetscCall(PetscFreeSpaceContiguous(&free_space, ptap->apj));
300:   PetscCall(PetscLLDestroy(lnk, lnkbt));

302:   /* malloc apa to store dense row A[i,:]*P */
303:   PetscCall(PetscCalloc1(pN, &ptap->apa));

305:   /* set and assemble symbolic parallel matrix C */
306:   PetscCall(MatSetSizes(C, am, pn, PETSC_DETERMINE, PETSC_DETERMINE));
307:   PetscCall(MatSetBlockSizesFromMats(C, A, P));

309:   PetscCall(MatGetType(A, &mtype));
310:   PetscCall(MatSetType(C, mtype));
311:   PetscCall(MatMPIAIJSetPreallocation(C, 0, dnz, 0, onz));
312:   MatPreallocateEnd(dnz, onz);

314:   PetscCall(MatSetValues_MPIAIJ_CopyFromCSRFormat_Symbolic(C, apj, api));
315:   C->nooffprocentries = PETSC_TRUE;
316:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
317:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
318:   C->nooffprocentries = nooffprocentries;
319:   PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));

321:   C->ops->matmultnumeric = MatMatMultNumeric_MPIAIJ_MPIAIJ_nonscalable;
322:   C->ops->productnumeric = MatProductNumeric_AB;

324:   /* attach the supporting struct to C for reuse */
325:   C->product->data    = ptap;
326:   C->product->destroy = MatProductCtxDestroy_MPIAIJ_MatMatMult;

328:   /* set MatInfo */
329:   afill = (PetscReal)api[am] / (adi[am] + aoi[am] + pi_loc[pm] + 1) + 1.e-5;
330:   if (afill < 1.0) afill = 1.0;
331:   C->info.mallocs           = nspacedouble;
332:   C->info.fill_ratio_given  = fill;
333:   C->info.fill_ratio_needed = afill;

335:   if (PetscDefined(USE_INFO)) {
336:     if (api[am]) {
337:       PetscCall(PetscInfo(C, "Reallocs %" PetscInt_FMT "; Fill ratio: given %g needed %g.\n", nspacedouble, (double)fill, (double)afill));
338:       PetscCall(PetscInfo(C, "Use MatMatMult(A,B,MatReuse,%g,&C) for best performance.;\n", (double)afill));
339:     } else PetscCall(PetscInfo(C, "Empty matrix product\n"));
340:   }
341:   PetscFunctionReturn(PETSC_SUCCESS);
342: }

344: static PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIDense(Mat, Mat, PetscReal, Mat);
345: static PetscErrorCode MatMatMultNumeric_MPIAIJ_MPIDense(Mat, Mat, Mat);

347: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_MPIDense_AB(Mat C)
348: {
349:   Mat_Product *product = C->product;
350:   Mat          A = product->A, B = product->B;

352:   PetscFunctionBegin;
353:   if (A->cmap->rstart != B->rmap->rstart || A->cmap->rend != B->rmap->rend)
354:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Matrix local dimensions are incompatible, (%" PetscInt_FMT ", %" PetscInt_FMT ") != (%" PetscInt_FMT ",%" PetscInt_FMT ")", A->cmap->rstart, A->cmap->rend, B->rmap->rstart, B->rmap->rend);

356:   C->ops->matmultsymbolic = MatMatMultSymbolic_MPIAIJ_MPIDense;
357:   C->ops->productsymbolic = MatProductSymbolic_AB;
358:   PetscFunctionReturn(PETSC_SUCCESS);
359: }

361: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_MPIDense_AtB(Mat C)
362: {
363:   Mat_Product *product = C->product;
364:   Mat          A = product->A, B = product->B;

366:   PetscFunctionBegin;
367:   if (A->rmap->rstart != B->rmap->rstart || A->rmap->rend != B->rmap->rend)
368:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Matrix local dimensions are incompatible, (%" PetscInt_FMT ", %" PetscInt_FMT ") != (%" PetscInt_FMT ",%" PetscInt_FMT ")", A->rmap->rstart, A->rmap->rend, B->rmap->rstart, B->rmap->rend);

370:   C->ops->transposematmultsymbolic = MatTransposeMatMultSymbolic_MPIAIJ_MPIDense;
371:   C->ops->productsymbolic          = MatProductSymbolic_AtB;
372:   PetscFunctionReturn(PETSC_SUCCESS);
373: }

375: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_MPIAIJ_MPIDense(Mat C)
376: {
377:   Mat_Product *product = C->product;

379:   PetscFunctionBegin;
380:   switch (product->type) {
381:   case MATPRODUCT_AB:
382:     PetscCall(MatProductSetFromOptions_MPIAIJ_MPIDense_AB(C));
383:     break;
384:   case MATPRODUCT_AtB:
385:     PetscCall(MatProductSetFromOptions_MPIAIJ_MPIDense_AtB(C));
386:     break;
387:   default:
388:     break;
389:   }
390:   PetscFunctionReturn(PETSC_SUCCESS);
391: }

393: PETSC_INTERN PetscErrorCode MatMPIDenseScatterDestroy_Private(MPIAIJ_MPIDense *contents)
394: {
395:   PetscFunctionBegin;
396:   PetscCall(MatDestroy(&contents->workB));
397:   PetscCall(MatDestroy(contents->packed));
398:   PetscCall(MatDestroy(contents->packed + 1));
399:   PetscCall(PetscSFDestroy(&contents->sf[0]));
400:   PetscCall(PetscSFDestroy(&contents->sf[1]));
401:   for (PetscInt i = 0; i < contents->nsends; i++) PetscCallMPI(MPI_Type_free(&contents->stype[i]));
402:   for (PetscInt i = 0; i < contents->nrecvs; i++) PetscCallMPI(MPI_Type_free(&contents->rtype[i]));
403:   PetscCall(PetscFree4(contents->stype, contents->rtype, contents->rwaits, contents->swaits));
404:   PetscFunctionReturn(PETSC_SUCCESS);
405: }

407: typedef struct {
408:   MPIAIJ_MPIDense scatter;
409:   Mat             workC; /* off-diagonal contribution A_o * workB on the device route, NULL otherwise */
410: } MPIAIJ_MPIDense_AB;

412: static PetscErrorCode MatMPIAIJ_MPIDenseDestroy(PetscCtxRt ctx)
413: {
414:   MPIAIJ_MPIDense_AB *data = *(MPIAIJ_MPIDense_AB **)ctx;

416:   PetscFunctionBegin;
417:   PetscCall(MatDestroy(&data->workC));
418:   PetscCall(MatMPIDenseScatterDestroy_Private(&data->scatter));
419:   PetscCall(PetscFree(data));
420:   PetscFunctionReturn(PETSC_SUCCESS);
421: }

423: /* Creates the parts of the scatter that depend on contents->blda: the strided PetscSFs on the device, the send datatypes on the host */
424: static PetscErrorCode MatMPIDenseScatterSetUpLDA_Private(VecScatter ctx, PetscInt bs, Mat B, MPIAIJ_MPIDense *contents)
425: {
426:   PetscInt        nrows = contents->workB->rmap->n;
427:   MPI_Datatype    type1;
428:   const PetscInt *sindices, *sstarts;
429:   PetscMPIInt    *disp;
430:   PetscMPIInt     nsends, nrows_to, bs_mpi;

432:   PetscFunctionBegin;
433:   if (contents->ondevice) {
434:     PetscCheck(ctx->vscat.bs <= 1 || contents->blda % ctx->vscat.bs == 0, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Leading dimension %" PetscInt_FMT " of the dense matrix must be a multiple of the block size %" PetscInt_FMT, contents->blda, ctx->vscat.bs);
435:     PetscCall(PetscSFCreateStridedSF(ctx, contents->ncols[0], contents->blda, nrows, &contents->sf[0]));
436:     if (contents->ncols[1] > 0) PetscCall(PetscSFCreateStridedSF(ctx, contents->ncols[1], contents->blda, nrows, &contents->sf[1]));
437:   } else {
438:     PetscCall(VecScatterGetRemote_Private(ctx, PETSC_TRUE, &nsends, &sstarts, &sindices, NULL, NULL));
439:     PetscCall(PetscMalloc1(PetscMax(B->rmap->n, 1), &disp));
440:     PetscCall(PetscMPIIntCast(bs, &bs_mpi));
441:     for (PetscMPIInt i = 0; i < nsends; i++) {
442:       PetscCall(PetscMPIIntCast(sstarts[i + 1] - sstarts[i], &nrows_to));
443:       for (PetscInt j = 0; j < nrows_to; j++) PetscCall(PetscMPIIntCast(sindices[sstarts[i] + j] * bs, &disp[j]));
444:       PetscCallMPI(MPI_Type_create_indexed_block(nrows_to, bs_mpi, disp, MPIU_SCALAR, &type1));
445:       PetscCallMPI(MPI_Type_create_resized(type1, 0, contents->blda * sizeof(PetscScalar), &contents->stype[i]));
446:       PetscCallMPI(MPI_Type_commit(&contents->stype[i]));
447:       PetscCallMPI(MPI_Type_free(&type1));
448:     }
449:     PetscCall(PetscFree(disp));
450:     PetscCall(VecScatterRestoreRemote_Private(ctx, PETSC_TRUE, &nsends, &sstarts, &sindices, NULL, NULL));
451:   }
452:   PetscFunctionReturn(PETSC_SUCCESS);
453: }

455: /* MatMPIDenseGetBatchSize_Private - Gets the number of columns of B to process at a time, to reduce the memory of a work matrix with nrows rows

457:    Collective

459:    Input Parameters:
460: +  nrows - number of rows of the work matrix on this process
461: .  Am    - number of local rows of the sparse matrix A of the product
462: .  B     - the MATMPIDENSE input matrix
463: -  C     - the product matrix, whose prefix is used for -matproduct_batch_size

465:    Output Parameters:
466: +  batchSize  - number of columns of B per batch; 0 or the number of columns of B means all the columns are processed at once
467: -  numBatches - number of full batches, or 0 if B is not split into batches; a smaller last batch holds the remaining columns

469:    Level: developer

471:    Note:
472:    Each process chooses a batch size that keeps its work matrix to about twice the memory of Am rows with all the columns of B,
473:    rounded down to a multiple of the column block size of B. A process with no work rows chooses all the columns. The largest
474:    choice over all processes is used, so B is split only if every process wants it split, unless -matproduct_batch_size gives another size.

476: .seealso: `MatMPIDenseScatterSetUp_Private()`, `MatTransposeMatMultSymbolic_MPIAIJ_MPIDense()`
477: */
478: PETSC_INTERN PetscErrorCode MatMPIDenseGetBatchSize_Private(PetscInt nrows, PetscInt Am, Mat B, Mat C, PetscInt *batchSize, PetscInt *numBatches)
479: {
480:   PetscInt BN = B->cmap->N, Bbn, Bbs, numBb;
481:   MPI_Comm comm;

483:   PetscFunctionBegin;
484:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
485:   if (nrows > 0) {
486:     Bbn = 2 * Am * BN / nrows;
487:     if (Bbn == 0) Bbn = 1;
488:   } else Bbn = BN;
489:   Bbs = B->cmap->bs;
490:   Bbn = Bbn / Bbs * Bbs;
491:   if (Bbn > BN) Bbn = BN;
492:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &Bbn, 1, MPIU_INT, MPI_MAX, comm));

494:   /* Enable runtime option for Bbn */
495:   PetscOptionsBegin(comm, ((PetscObject)C)->prefix, "MatProduct", "Mat");
496:   PetscCall(PetscOptionsDeprecated("-matmatmult_Bbn", "-matproduct_batch_size", "3.25", NULL));
497:   PetscCall(PetscOptionsBoundedInt("-matproduct_batch_size", "Number of dense columns per batch", "MatProduct", Bbn, &Bbn, NULL, 0));
498:   PetscOptionsEnd();
499:   Bbn = PetscMin(Bbn, BN);

501:   if (Bbn > 0 && Bbn < BN) numBb = BN / Bbn;
502:   else numBb = 0;
503:   if (numBb > 0) PetscCall(PetscInfo(C, "Using column batches of size %" PetscInt_FMT " for %" PetscInt_FMT " dense columns\n", Bbn, BN));
504:   *batchSize  = Bbn;
505:   *numBatches = numBb;
506:   PetscFunctionReturn(PETSC_SUCCESS);
507: }

509: PETSC_INTERN PetscErrorCode MatMPIDenseScatterSetUp_Private(VecScatter ctx, PetscInt nrows, PetscInt bs, PetscInt Am, Mat B, Mat C, MPIAIJ_MPIDense *contents, PetscInt *batchSize, PetscInt *numBatches)
510: {
511:   PetscInt        BN = B->cmap->N, Bbn, numBb, ncols;
512:   MPI_Datatype    type1;
513:   const PetscInt *rstarts;
514:   PetscMPIInt     nsends, nrecvs, nrows_from, disp = 0;
515:   PetscBool       flg;

517:   PetscFunctionBegin;
518:   PetscCall(MatDenseGetLDA(B, &contents->blda));
519:   PetscCall(PetscObjectGetId((PetscObject)B, contents->bid));
520:   /* Create column block of B and C for memory scalability when BN is too large */
521:   PetscCall(MatMPIDenseGetBatchSize_Private(nrows, Am, B, C, &Bbn, &numBb));
522:   ncols = Bbn > 0 ? Bbn : BN;

524:   /* Create work matrix used to store off processor rows of B needed for local product, with the same type as the local block of B */
525:   PetscCall(MatCreate(PETSC_COMM_SELF, &contents->workB));
526:   PetscCall(MatSetSizes(contents->workB, nrows, ncols, nrows, ncols));
527:   PetscCall(MatSetType(contents->workB, ((PetscObject)((Mat_MPIDense *)B->data)->A)->type_name));
528:   PetscCall(MatSetUp(contents->workB));

530:   PetscCall(PetscObjectTypeCompare((PetscObject)((Mat_MPIDense *)B->data)->A, MATSEQDENSE, &flg));
531:   contents->ondevice = (PetscBool)!flg;
532:   if (contents->ondevice) {
533:     /* Use strided PetscSFs, which support device memory, instead of the MPI derived data types below */
534:     contents->ncols[0] = ncols;
535:     if (numBb > 0 && BN % Bbn != 0) contents->ncols[1] = BN % Bbn;
536:   } else {
537:     PetscCall(VecScatterGetRemote_Private(ctx, PETSC_TRUE, &nsends, NULL, NULL, NULL, NULL));
538:     PetscCall(VecScatterGetRemoteOrdered_Private(ctx, PETSC_FALSE, &nrecvs, &rstarts, NULL, NULL, NULL));

540:     /* Use MPI derived data type to reduce memory required by the send/recv buffers */
541:     PetscCall(PetscMalloc4(nsends, &contents->stype, nrecvs, &contents->rtype, nrecvs, &contents->rwaits, nsends, &contents->swaits));
542:     contents->nsends = nsends;
543:     contents->nrecvs = nrecvs;

545:     for (PetscMPIInt i = 0; i < nrecvs; i++) {
546:       /* received values from a process form a (nrows_from x Bbn) row block in workB (column-wise) */
547:       PetscCall(PetscMPIIntCast((rstarts[i + 1] - rstarts[i]) * bs, &nrows_from));
548:       PetscCallMPI(MPI_Type_create_indexed_block(1, nrows_from, &disp, MPIU_SCALAR, &type1));
549:       PetscCallMPI(MPI_Type_create_resized(type1, 0, nrows * sizeof(PetscScalar), &contents->rtype[i]));
550:       PetscCallMPI(MPI_Type_commit(&contents->rtype[i]));
551:       PetscCallMPI(MPI_Type_free(&type1));
552:     }

554:     PetscCall(VecScatterRestoreRemote_Private(ctx, PETSC_TRUE /*send*/, &nsends, NULL, NULL, NULL, NULL));
555:     PetscCall(VecScatterRestoreRemoteOrdered_Private(ctx, PETSC_FALSE /*recv*/, &nrecvs, &rstarts, NULL, NULL, NULL));
556:   }
557:   PetscCall(MatMPIDenseScatterSetUpLDA_Private(ctx, bs, B, contents));
558:   if (batchSize) *batchSize = Bbn;
559:   if (numBatches) *numBatches = numBb;
560:   PetscFunctionReturn(PETSC_SUCCESS);
561: }

563: /* Recreates the parts of the scatter that depend on the leading dimension when a new input B has a different one */
564: PETSC_INTERN PetscErrorCode MatMPIDenseScatterUpdateLDA_Private(VecScatter ctx, PetscInt bs, Mat B, Mat C, MPIAIJ_MPIDense *contents)
565: {
566:   PetscObjectId id;
567:   PetscInt      blda;
568:   PetscBool     update;

570:   PetscFunctionBegin;
571:   PetscCall(PetscObjectGetId((PetscObject)B, &id));
572:   /* alternating between two validated inputs can reuse the strided PetscSF without another reduction */
573:   if (contents->ondevice == PETSC_TRUE && (id == contents->bid[0] || id == contents->bid[1])) PetscFunctionReturn(PETSC_SUCCESS);
574:   PetscCall(MatDenseGetLDA(B, &blda));
575:   update = (PetscBool)(blda != contents->blda);
576:   if (contents->ondevice) PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &update, 1, MPI_C_BOOL, MPI_LOR, PetscObjectComm((PetscObject)C)));
577:   if (update) {
578:     PetscCall(PetscInfo(C, "Setting up the scatter again for a dense input with leading dimension %" PetscInt_FMT " instead of %" PetscInt_FMT "\n", blda, contents->blda));
579:     PetscCall(PetscSFDestroy(&contents->sf[0]));
580:     PetscCall(PetscSFDestroy(&contents->sf[1]));
581:     for (PetscInt i = 0; i < contents->nsends; i++) PetscCallMPI(MPI_Type_free(&contents->stype[i]));
582:     PetscCall(MatDestroy(contents->packed));
583:     PetscCall(MatDestroy(contents->packed + 1));
584:     contents->blda = blda;
585:     PetscCall(MatMPIDenseScatterSetUpLDA_Private(ctx, bs, B, contents));
586:   }
587:   contents->bid[1] = update == PETSC_TRUE ? 0 : contents->bid[0];
588:   contents->bid[0] = id;
589:   PetscFunctionReturn(PETSC_SUCCESS);
590: }

592: static PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIDense(Mat A, Mat B, PetscReal fill, Mat C)
593: {
594:   Mat_MPIAIJ         *aij = (Mat_MPIAIJ *)A->data;
595:   MPIAIJ_MPIDense_AB *data;
596:   PetscInt            nz  = aij->B->cmap->n;
597:   VecScatter          ctx = aij->Mvctx;
598:   PetscInt            Am = A->rmap->n, BN = B->cmap->N, Bbn, numBb;
599:   Mat                 workB1, workC1;
600:   const char         *ctype;

602:   PetscFunctionBegin;
603:   MatCheckProduct(C, 4);
604:   PetscCheck(!C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data not empty");
605:   PetscCall(MatDenseSetUpProduct_Private(C, A->rmap, B->cmap, B, NULL));
606:   /* The cuSPARSE and hipSPARSE symbolic below re-types a host local block of C in place, so capture the type
607:      of the local block of C now to give the work matrix the type the numeric will add it to */
608:   ctype = ((PetscObject)((Mat_MPIDense *)C->data)->A)->type_name;
609:   PetscCall(PetscNew(&data));
610:   PetscCall(MatMPIDenseScatterSetUp_Private(ctx, nz, 1, Am, B, C, &data->scatter, &Bbn, &numBb));
611:   PetscCall(MatProductClear(aij->A));
612:   PetscCall(MatProductClear(((Mat_MPIDense *)B->data)->A));
613:   PetscCall(MatProductClear(((Mat_MPIDense *)C->data)->A));
614:   if (data->scatter.ondevice && nz) {
615:     /* On the device route the off-diagonal contribution is computed into a work matrix and added to the local
616:        block of C, rather than accumulated in place by a host kernel */
617:     PetscCall(MatCreate(PETSC_COMM_SELF, &data->workC));
618:     PetscCall(MatSetSizes(data->workC, Am, Bbn ? Bbn : BN, Am, Bbn ? Bbn : BN));
619:     PetscCall(MatSetType(data->workC, ctype));
620:     PetscCall(MatSetUp(data->workC));
621:     PetscCall(MatProductCreateWithMat(aij->B, data->scatter.workB, NULL, data->workC));
622:     PetscCall(MatProductSetType(data->workC, MATPRODUCT_AB));
623:     PetscCall(MatProductSetFromOptions(data->workC));
624:     PetscCall(MatProductSymbolic(data->workC));
625:     if (numBb && BN % Bbn) {
626:       /* the last column batch is smaller, set up the product on the sub-matrices the numeric will use for it */
627:       PetscCall(MatDenseGetSubMatrix(data->scatter.workB, PETSC_DECIDE, PETSC_DECIDE, 0, BN % Bbn, &workB1));
628:       PetscCall(MatDenseGetSubMatrix(data->workC, PETSC_DECIDE, PETSC_DECIDE, 0, BN % Bbn, &workC1));
629:       PetscCall(MatProductCreateWithMat(aij->B, workB1, NULL, workC1));
630:       PetscCall(MatProductSetType(workC1, MATPRODUCT_AB));
631:       PetscCall(MatProductSetFromOptions(workC1));
632:       PetscCall(MatProductSymbolic(workC1));
633:       PetscCall(MatDenseRestoreSubMatrix(data->workC, &workC1));
634:       PetscCall(MatDenseRestoreSubMatrix(data->scatter.workB, &workB1));
635:     }
636:   }
637:   PetscCall(MatProductCreateWithMat(aij->A, ((Mat_MPIDense *)B->data)->A, NULL, ((Mat_MPIDense *)C->data)->A));
638:   PetscCall(MatProductSetType(((Mat_MPIDense *)C->data)->A, MATPRODUCT_AB));
639:   PetscCall(MatProductSetFromOptions(((Mat_MPIDense *)C->data)->A));
640:   PetscCall(MatProductSymbolic(((Mat_MPIDense *)C->data)->A));
641:   C->product->data       = data;
642:   C->product->destroy    = MatMPIAIJ_MPIDenseDestroy;
643:   C->ops->matmultnumeric = MatMatMultNumeric_MPIAIJ_MPIDense;
644:   PetscFunctionReturn(PETSC_SUCCESS);
645: }

647: PETSC_INTERN PetscErrorCode MatMatMultNumericAdd_SeqAIJ_SeqDense(Mat, Mat, Mat, const PetscBool);

649: /*
650:     Performs an efficient scatter on the rows of B needed by this process; this is
651:     a modification of the VecScatterBegin_() routines.
652: */
653: static PetscErrorCode MatMPIDenseScatterHost_Private(VecScatter ctx, PetscInt bs, Mat workB, MPIAIJ_MPIDense *contents, Mat B, Mat C)
654: {
655:   const PetscScalar *b;
656:   PetscScalar       *rvalues;
657:   const PetscInt    *sindices, *sstarts, *rstarts;
658:   const PetscMPIInt *sprocs, *rprocs;
659:   PetscMPIInt        nsends, nrecvs;
660:   MPI_Comm           comm;
661:   PetscMPIInt        tag = ((PetscObject)ctx)->tag, ncols, nsends_mpi, nrecvs_mpi;

663:   PetscFunctionBegin;
664:   PetscCall(PetscMPIIntCast(B->cmap->N, &ncols));
665:   PetscCall(VecScatterGetRemote_Private(ctx, PETSC_TRUE /*send*/, &nsends, &sstarts, &sindices, &sprocs, NULL /*bs*/));
666:   PetscCall(VecScatterGetRemoteOrdered_Private(ctx, PETSC_FALSE /*recv*/, &nrecvs, &rstarts, NULL, &rprocs, NULL /*bs*/));
667:   PetscCall(PetscMPIIntCast(nsends, &nsends_mpi));
668:   PetscCall(PetscMPIIntCast(nrecvs, &nrecvs_mpi));

670:   PetscCall(MatDenseGetArrayRead(B, &b));
671:   PetscCall(MatDenseGetArray(workB, &rvalues));

673:   /* Post recv, use MPI derived data type to save memory */
674:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
675:   for (PetscMPIInt i = 0; i < nrecvs; i++) PetscCallMPI(MPIU_Irecv(rvalues + ((rstarts[i] - rstarts[0]) * bs), ncols, contents->rtype[i], rprocs[i], tag, comm, contents->rwaits + i));
676:   for (PetscMPIInt i = 0; i < nsends; i++) PetscCallMPI(MPIU_Isend(b, ncols, contents->stype[i], sprocs[i], tag, comm, contents->swaits + i));

678:   if (nrecvs) PetscCallMPI(MPI_Waitall(nrecvs_mpi, contents->rwaits, MPI_STATUSES_IGNORE));
679:   if (nsends) PetscCallMPI(MPI_Waitall(nsends_mpi, contents->swaits, MPI_STATUSES_IGNORE));

681:   PetscCall(VecScatterRestoreRemote_Private(ctx, PETSC_TRUE /*send*/, &nsends, &sstarts, &sindices, &sprocs, NULL));
682:   PetscCall(VecScatterRestoreRemoteOrdered_Private(ctx, PETSC_FALSE /*recv*/, &nrecvs, &rstarts, NULL, &rprocs, NULL));
683:   PetscCall(MatDenseRestoreArrayRead(B, &b));
684:   PetscCall(MatDenseRestoreArray(workB, &rvalues));
685:   PetscFunctionReturn(PETSC_SUCCESS);
686: }

688: /*
689:    Same as MatMPIDenseScatterHost_Private(), but using the strided PetscSFs set up in
690:    MatMPIDenseScatterSetUp_Private() so that the data never leaves the device. The scatter is split in two
691:    halves so that a caller can run other work while the off-process rows of B are in flight
692: */
693: static PetscErrorCode MatMPIDenseScatterDeviceBegin_Private(Mat workB, MPIAIJ_MPIDense *contents, Mat B)
694: {
695:   PetscSF      sf;
696:   PetscInt     k = 0, blda;
697:   PetscMemType bmtype, wmtype;

699:   PetscFunctionBegin;
700:   PetscCheck(!contents->sfinuse, PETSC_COMM_SELF, PETSC_ERR_PLIB, "A scatter is already in flight");
701:   if (B->cmap->N != contents->ncols[0]) k = 1;
702:   PetscCheck(contents->sf[k] && contents->ncols[k] == B->cmap->N, PETSC_COMM_SELF, PETSC_ERR_PLIB, "No scatter set up for %" PetscInt_FMT " columns", B->cmap->N);
703:   sf = contents->sf[k];
704:   PetscCall(MatDenseGetLDA(B, &blda));
705:   /* a validated input can change its stride on a single process; pack only on processes where the strided PetscSF differs */
706:   if (blda != contents->blda && B->cmap->N > 1) {
707:     PetscCall(MatDestroy(&contents->packed[k]));
708:     PetscCall(MatDenseDuplicateLocalWithLDA_Private(B, contents->blda, &contents->packed[k]));
709:     B = contents->packed[k];
710:   } else PetscCall(MatDenseGetLocalMatrix(B, &B));
711:   contents->source = B;
712:   /* every entry of workB is overwritten, so write-only access is enough */
713:   PetscCall(MatDenseGetArrayReadAndMemType(B, &contents->barray, &bmtype));
714:   PetscCall(MatDenseGetArrayWriteAndMemType(workB, &contents->warray, &wmtype));
715:   PetscCall(PetscSFBcastWithMemTypeBegin(sf, sf->vscat.unit, bmtype, contents->barray, wmtype, contents->warray, MPI_REPLACE));
716:   contents->sfinuse = sf;
717:   PetscFunctionReturn(PETSC_SUCCESS);
718: }

720: static PetscErrorCode MatMPIDenseScatterDeviceEnd_Private(Mat workB, MPIAIJ_MPIDense *contents)
721: {
722:   PetscSF sf = contents->sfinuse;

724:   PetscFunctionBegin;
725:   PetscCheck(sf, PETSC_COMM_SELF, PETSC_ERR_PLIB, "No scatter in flight");
726:   PetscCall(PetscSFBcastEnd(sf, sf->vscat.unit, contents->barray, contents->warray, MPI_REPLACE));
727:   PetscCall(MatDenseRestoreArrayWriteAndMemType(workB, &contents->warray));
728:   PetscCall(MatDenseRestoreArrayReadAndMemType(contents->source, &contents->barray));
729:   contents->sfinuse = NULL;
730:   PetscFunctionReturn(PETSC_SUCCESS);
731: }

733: /*
734:    The checks the host and device scatters share; on the device route they are done by the begin half
735: */
736: static PetscErrorCode MatMPIDenseScatterCheck_Private(PetscInt nrows, Mat workB, Mat C)
737: {
738:   PetscFunctionBegin;
739:   MatCheckProduct(C, 3);
740:   PetscCheck(C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data empty");
741:   PetscCheck(nrows == workB->rmap->n, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Number of rows of workB %" PetscInt_FMT " not equal to columns of off-diagonal block %" PetscInt_FMT, workB->rmap->n, nrows);
742:   PetscFunctionReturn(PETSC_SUCCESS);
743: }

745: PETSC_INTERN PetscErrorCode MatMPIDenseScatter_Private(VecScatter ctx, PetscInt nrows, PetscInt bs, Mat workB, MPIAIJ_MPIDense *contents, Mat B, Mat C)
746: {
747:   PetscFunctionBegin;
748:   PetscCall(MatMPIDenseScatterCheck_Private(nrows, workB, C));
749:   if (contents->ondevice) {
750:     PetscCall(MatMPIDenseScatterDeviceBegin_Private(workB, contents, B));
751:     PetscCall(MatMPIDenseScatterDeviceEnd_Private(workB, contents));
752:   } else PetscCall(MatMPIDenseScatterHost_Private(ctx, bs, workB, contents, B, C));
753:   PetscFunctionReturn(PETSC_SUCCESS);
754: }

756: /*
757:    Starts the scatter of the off-process rows of B into workB. On the device route only the begin half of the
758:    PetscSF broadcast is posted, so the caller must complete it with MatMPIDenseScatterEnd(); the host scatter
759:    is blocking and is done entirely here
760: */
761: static PetscErrorCode MatMPIDenseScatterBegin(Mat A, Mat B, Mat workB, Mat C)
762: {
763:   Mat_MPIAIJ      *aij      = (Mat_MPIAIJ *)A->data;
764:   MPIAIJ_MPIDense *contents = &((MPIAIJ_MPIDense_AB *)C->product->data)->scatter;

766:   PetscFunctionBegin;
767:   if (contents->ondevice) {
768:     PetscCall(MatMPIDenseScatterCheck_Private(aij->B->cmap->n, workB, C));
769:     PetscCall(MatMPIDenseScatterDeviceBegin_Private(workB, contents, B));
770:   } else PetscCall(MatMPIDenseScatter_Private(aij->Mvctx, aij->B->cmap->n, 1, workB, contents, B, C));
771:   PetscFunctionReturn(PETSC_SUCCESS);
772: }

774: static PetscErrorCode MatMPIDenseScatterEnd(Mat workB, Mat C)
775: {
776:   MPIAIJ_MPIDense *contents = &((MPIAIJ_MPIDense_AB *)C->product->data)->scatter;

778:   PetscFunctionBegin;
779:   if (contents->ondevice) PetscCall(MatMPIDenseScatterDeviceEnd_Private(workB, contents));
780:   PetscFunctionReturn(PETSC_SUCCESS);
781: }

783: /* MatMPIAIJ_MPIDenseProductNumeric_Private - Computes C = A B or C = A^T B for the sequential matrices inside a MATMPIAIJ times MATMPIDENSE product

785:    Not Collective

787:    Input Parameters:
788: +  A     - a diagonal or off-diagonal block of the MATMPIAIJ matrix
789: .  B     - the sequential dense input: the local block of B, one batch of its columns, or the off-process rows of B
790: .  C     - the sequential dense result, whose product is set up here if it has none
791: .  ptype - MATPRODUCT_AB or MATPRODUCT_AtB
792: -  clear - whether to clear the product of C after the numeric phase, so that the next call sets it up again

794:    Level: developer

796:    Note:
797:    The product is also set up again when A is not the matrix it was set up with, since its symbolic phase may keep data built from A.

799: .seealso: `MatMatMultNumeric_MPIAIJ_MPIDense()`, `MatTransposeMatMultNumeric_MPIAIJ_MPIDense()`, `MatProductClear()`
800: */
801: PETSC_INTERN PetscErrorCode MatMPIAIJ_MPIDenseProductNumeric_Private(Mat A, Mat B, Mat C, MatProductType ptype, PetscBool clear)
802: {
803:   PetscFunctionBegin;
804:   if (C->product != NULL && C->product->A != A) PetscCall(MatProductClear(C));
805:   if (C->product == NULL) {
806:     PetscCall(MatProductCreateWithMat(A, B, NULL, C));
807:     PetscCall(MatProductSetType(C, ptype));
808:     PetscCall(MatProductSetFromOptions(C));
809:     PetscCall(MatProductSymbolic(C));
810:   } else PetscCall(MatProductReplaceMats(A, B, NULL, C));
811:   if (clear && !C->product->clear) C->product->clear = PETSC_TRUE;
812:   PetscCall(MatProductNumeric(C));
813:   PetscFunctionReturn(PETSC_SUCCESS);
814: }

816: static PetscErrorCode MatMatMultNumeric_MPIAIJ_MPIDense(Mat A, Mat B, Mat C)
817: {
818:   Mat_MPIAIJ         *aij    = (Mat_MPIAIJ *)A->data;
819:   Mat_MPIDense       *bdense = (Mat_MPIDense *)B->data;
820:   Mat_MPIDense       *cdense = (Mat_MPIDense *)C->data;
821:   Mat                 workB;
822:   MPIAIJ_MPIDense    *contents;
823:   MPIAIJ_MPIDense_AB *data;
824:   PetscBool           clear = PETSC_FALSE, flg, overlap;

826:   PetscFunctionBegin;
827:   MatCheckProduct(C, 3);
828:   PetscCheck(C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Product data empty");
829:   data     = (MPIAIJ_MPIDense_AB *)C->product->data;
830:   contents = &data->scatter;
831:   if (PetscDefined(HAVE_CUPM)) {
832:     PetscCall(PetscObjectTypeCompare((PetscObject)C, MATMPIDENSE, &flg));
833:     if (flg) PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMPIAIJ, &flg));
834:     clear = (PetscBool)!flg; /* if either A or C is a device Mat, make sure MatProductClear() is called */
835:   }
836:   /* The device scatter is non-blocking, so when there are no column batches start it before the product of the
837:      diagonal block below to overlap the communication with that product, as MatMult_MPIAIJ() does. The host
838:      scatter is blocking, so it is left where it is */
839:   PetscCall(MatMPIDenseScatterUpdateLDA_Private(aij->Mvctx, 1, B, C, contents));
840:   overlap = (PetscBool)(contents->ondevice && contents->workB->cmap->n == B->cmap->N);
841:   if (overlap) PetscCall(MatMPIDenseScatterBegin(A, B, contents->workB, C));
842:   /* diagonal block of A times all local rows of B, first make sure that everything is up-to-date */
843:   PetscCall(MatMPIAIJ_MPIDenseProductNumeric_Private(aij->A, bdense->A, cdense->A, MATPRODUCT_AB, clear));
844:   if (contents->workB->cmap->n == B->cmap->N) {
845:     /* get off processor parts of B needed to complete C=A*B */
846:     workB = contents->workB;
847:     if (!overlap) PetscCall(MatMPIDenseScatterBegin(A, B, workB, C));
848:     PetscCall(MatMPIDenseScatterEnd(workB, C));

850:     /* off-diagonal block of A times nonlocal rows of B */
851:     if (data->workC) {
852:       PetscCall(MatMPIAIJ_MPIDenseProductNumeric_Private(aij->B, workB, data->workC, MATPRODUCT_AB, clear));
853:       PetscCall(MatAXPY(cdense->A, 1.0, data->workC, SAME_NONZERO_PATTERN));
854:     } else if (!contents->ondevice) PetscCall(MatMatMultNumericAdd_SeqAIJ_SeqDense(aij->B, workB, cdense->A, PETSC_TRUE)); /* the device route has no work matrix only when the off-diagonal block has no columns */
855:   } else {
856:     Mat       Bb, Cb, workC;
857:     PetscInt  BN = B->cmap->N, n = contents->workB->cmap->n, cols;
858:     PetscBool ccpu = PETSC_FALSE;

860:     PetscCheck(n > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Column block size %" PetscInt_FMT " must be positive", n);
861:     /* The host route accumulates into the local block of C on the host, bind C to the CPU to avoid copies back
862:        and forth from the device when getting and restoring the sub-matrices */
863:     if (!contents->ondevice) {
864:       PetscCall(MatBoundToCPU(C, &ccpu));
865:       PetscCall(MatBindToCPU(C, PETSC_TRUE));
866:     }
867:     for (PetscInt i = 0; i < BN; i += n) {
868:       cols  = PetscMin(n, BN - i);
869:       workB = contents->workB;
870:       workC = data->workC;
871:       if (cols != n) {
872:         PetscCall(MatDenseGetSubMatrix(contents->workB, PETSC_DECIDE, PETSC_DECIDE, 0, cols, &workB));
873:         if (workC) PetscCall(MatDenseGetSubMatrix(data->workC, PETSC_DECIDE, PETSC_DECIDE, 0, cols, &workC));
874:       }
875:       PetscCall(MatDenseGetSubMatrix(B, PETSC_DECIDE, PETSC_DECIDE, i, i + cols, &Bb));
876:       PetscCall(MatDenseGetSubMatrix(C, PETSC_DECIDE, PETSC_DECIDE, i, i + cols, &Cb));

878:       /* get off processor parts of B needed to complete C=A*B */
879:       PetscCall(MatMPIDenseScatterBegin(A, Bb, workB, C));
880:       PetscCall(MatMPIDenseScatterEnd(workB, C));

882:       /* off-diagonal block of A times nonlocal rows of B */
883:       if (workC) {
884:         PetscCall(MatMPIAIJ_MPIDenseProductNumeric_Private(aij->B, workB, workC, MATPRODUCT_AB, clear));
885:         PetscCall(MatAXPY(((Mat_MPIDense *)Cb->data)->A, 1.0, workC, SAME_NONZERO_PATTERN));
886:       } else if (!contents->ondevice) PetscCall(MatMatMultNumericAdd_SeqAIJ_SeqDense(aij->B, workB, ((Mat_MPIDense *)Cb->data)->A, PETSC_TRUE));
887:       if (cols != n) {
888:         if (workC) PetscCall(MatDenseRestoreSubMatrix(data->workC, &workC));
889:         PetscCall(MatDenseRestoreSubMatrix(contents->workB, &workB));
890:       }
891:       PetscCall(MatDenseRestoreSubMatrix(B, &Bb));
892:       PetscCall(MatDenseRestoreSubMatrix(C, &Cb));
893:     }
894:     if (!contents->ondevice) PetscCall(MatBindToCPU(C, ccpu));
895:   }
896:   PetscFunctionReturn(PETSC_SUCCESS);
897: }

899: PetscErrorCode MatMatMultNumeric_MPIAIJ_MPIAIJ(Mat A, Mat P, Mat C)
900: {
901:   Mat_MPIAIJ          *a = (Mat_MPIAIJ *)A->data, *c = (Mat_MPIAIJ *)C->data;
902:   Mat_SeqAIJ          *ad = (Mat_SeqAIJ *)a->A->data, *ao = (Mat_SeqAIJ *)a->B->data;
903:   Mat_SeqAIJ          *cd = (Mat_SeqAIJ *)c->A->data, *co = (Mat_SeqAIJ *)c->B->data;
904:   PetscInt            *adi = ad->i, *adj, *aoi = ao->i, *aoj;
905:   PetscScalar         *ada, *aoa, *cda = cd->a, *coa = co->a;
906:   Mat_SeqAIJ          *p_loc, *p_oth;
907:   PetscInt            *pi_loc, *pj_loc, *pi_oth, *pj_oth, *pj;
908:   PetscScalar         *pa_loc, *pa_oth, *pa, valtmp, *ca;
909:   PetscInt             cm = C->rmap->n, anz, pnz;
910:   MatProductCtx_APMPI *ptap;
911:   PetscScalar         *apa_sparse;
912:   const PetscScalar   *dummy;
913:   PetscInt            *api, *apj, *apJ, i, j, k, row;
914:   PetscInt             cstart = C->cmap->rstart;
915:   PetscInt             cdnz, conz, k0, k1, nextp;
916:   MPI_Comm             comm;
917:   PetscMPIInt          size;
918:   const PetscBool      nooffprocentries = C->nooffprocentries;

920:   PetscFunctionBegin;
921:   MatCheckProduct(C, 3);
922:   ptap = (MatProductCtx_APMPI *)C->product->data;
923:   PetscCheck(ptap, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtAP cannot be computed. Missing data");
924:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
925:   PetscCallMPI(MPI_Comm_size(comm, &size));
926:   PetscCheck(ptap->P_oth || size <= 1, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "AP cannot be reused. Do not call MatProductClear()");

928:   /* flag CPU mask for C */
929: #if PetscDefined(HAVE_DEVICE)
930:   if (C->offloadmask != PETSC_OFFLOAD_UNALLOCATED) C->offloadmask = PETSC_OFFLOAD_CPU;
931:   if (c->A->offloadmask != PETSC_OFFLOAD_UNALLOCATED) c->A->offloadmask = PETSC_OFFLOAD_CPU;
932:   if (c->B->offloadmask != PETSC_OFFLOAD_UNALLOCATED) c->B->offloadmask = PETSC_OFFLOAD_CPU;
933: #endif
934:   apa_sparse = ptap->apa;

936:   /* 1) get P_oth = ptap->P_oth  and P_loc = ptap->P_loc */
937:   /* update numerical values of P_oth and P_loc */
938:   PetscCall(MatGetBrowsOfAoCols_MPIAIJ(A, P, MAT_REUSE_MATRIX, &ptap->startsj_s, &ptap->startsj_r, &ptap->bufa, &ptap->P_oth));
939:   PetscCall(MatMPIAIJGetLocalMat(P, MAT_REUSE_MATRIX, &ptap->P_loc));

941:   /* 2) compute numeric C_loc = A_loc*P = Ad*P_loc + Ao*P_oth */
942:   /* get data from symbolic products */
943:   p_loc  = (Mat_SeqAIJ *)ptap->P_loc->data;
944:   pi_loc = p_loc->i;
945:   pj_loc = p_loc->j;
946:   pa_loc = p_loc->a;
947:   if (size > 1) {
948:     p_oth  = (Mat_SeqAIJ *)ptap->P_oth->data;
949:     pi_oth = p_oth->i;
950:     pj_oth = p_oth->j;
951:     pa_oth = p_oth->a;
952:   } else {
953:     p_oth  = NULL;
954:     pi_oth = NULL;
955:     pj_oth = NULL;
956:     pa_oth = NULL;
957:   }

959:   /* trigger copy to CPU */
960:   PetscCall(MatSeqAIJGetArrayRead(a->A, &dummy));
961:   PetscCall(MatSeqAIJRestoreArrayRead(a->A, &dummy));
962:   PetscCall(MatSeqAIJGetArrayRead(a->B, &dummy));
963:   PetscCall(MatSeqAIJRestoreArrayRead(a->B, &dummy));
964:   api = ptap->api;
965:   apj = ptap->apj;
966:   for (i = 0; i < cm; i++) {
967:     apJ = apj + api[i];

969:     /* diagonal portion of A */
970:     anz = adi[i + 1] - adi[i];
971:     adj = ad->j + adi[i];
972:     ada = ad->a + adi[i];
973:     for (j = 0; j < anz; j++) {
974:       row = adj[j];
975:       pnz = pi_loc[row + 1] - pi_loc[row];
976:       pj  = pj_loc + pi_loc[row];
977:       pa  = pa_loc + pi_loc[row];
978:       /* perform sparse axpy */
979:       valtmp = ada[j];
980:       nextp  = 0;
981:       for (k = 0; nextp < pnz; k++) {
982:         if (apJ[k] == pj[nextp]) { /* column of AP == column of P */
983:           apa_sparse[k] += valtmp * pa[nextp++];
984:         }
985:       }
986:       PetscCall(PetscLogFlops(2.0 * pnz));
987:     }

989:     /* off-diagonal portion of A */
990:     anz = aoi[i + 1] - aoi[i];
991:     aoj = PetscSafePointerPlusOffset(ao->j, aoi[i]);
992:     aoa = PetscSafePointerPlusOffset(ao->a, aoi[i]);
993:     for (j = 0; j < anz; j++) {
994:       row = aoj[j];
995:       pnz = pi_oth[row + 1] - pi_oth[row];
996:       pj  = pj_oth + pi_oth[row];
997:       pa  = pa_oth + pi_oth[row];
998:       /* perform sparse axpy */
999:       valtmp = aoa[j];
1000:       nextp  = 0;
1001:       for (k = 0; nextp < pnz; k++) {
1002:         if (apJ[k] == pj[nextp]) { /* column of AP == column of P */
1003:           apa_sparse[k] += valtmp * pa[nextp++];
1004:         }
1005:       }
1006:       PetscCall(PetscLogFlops(2.0 * pnz));
1007:     }

1009:     /* set values in C */
1010:     cdnz = cd->i[i + 1] - cd->i[i];
1011:     conz = co->i[i + 1] - co->i[i];

1013:     /* 1st off-diagonal part of C */
1014:     ca = PetscSafePointerPlusOffset(coa, co->i[i]);
1015:     k  = 0;
1016:     for (k0 = 0; k0 < conz; k0++) {
1017:       if (apJ[k] >= cstart) break;
1018:       ca[k0]        = apa_sparse[k];
1019:       apa_sparse[k] = 0.0;
1020:       k++;
1021:     }

1023:     /* diagonal part of C */
1024:     ca = cda + cd->i[i];
1025:     for (k1 = 0; k1 < cdnz; k1++) {
1026:       ca[k1]        = apa_sparse[k];
1027:       apa_sparse[k] = 0.0;
1028:       k++;
1029:     }

1031:     /* 2nd off-diagonal part of C */
1032:     ca = PetscSafePointerPlusOffset(coa, co->i[i]);
1033:     for (; k0 < conz; k0++) {
1034:       ca[k0]        = apa_sparse[k];
1035:       apa_sparse[k] = 0.0;
1036:       k++;
1037:     }
1038:   }
1039:   C->nooffprocentries = PETSC_TRUE;
1040:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
1041:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
1042:   C->nooffprocentries = nooffprocentries;
1043:   PetscFunctionReturn(PETSC_SUCCESS);
1044: }

1046: /* same as MatMatMultSymbolic_MPIAIJ_MPIAIJ_nonscalable(), except using LLCondensed to avoid O(BN) memory requirement */
1047: PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIAIJ(Mat A, Mat P, PetscReal fill, Mat C)
1048: {
1049:   MPI_Comm             comm;
1050:   PetscMPIInt          size;
1051:   MatProductCtx_APMPI *ptap;
1052:   PetscFreeSpaceList   free_space = NULL, current_space = NULL;
1053:   Mat_MPIAIJ          *a  = (Mat_MPIAIJ *)A->data;
1054:   Mat_SeqAIJ          *ad = (Mat_SeqAIJ *)a->A->data, *ao = (Mat_SeqAIJ *)a->B->data, *p_loc, *p_oth;
1055:   PetscInt            *pi_loc, *pj_loc, *pi_oth, *pj_oth, *dnz, *onz;
1056:   PetscInt            *adi = ad->i, *adj = ad->j, *aoi = ao->i, *aoj = ao->j, rstart = A->rmap->rstart;
1057:   PetscInt             i, pnz, row, *api, *apj, *Jptr, apnz, nspacedouble = 0, j, nzi, *lnk, apnz_max = 1;
1058:   PetscInt             am = A->rmap->n, pn = P->cmap->n, pm = P->rmap->n, lsize = pn + 20;
1059:   PetscReal            afill;
1060:   MatType              mtype;
1061:   const PetscBool      nooffprocentries = C->nooffprocentries;

1063:   PetscFunctionBegin;
1064:   MatCheckProduct(C, 4);
1065:   PetscCheck(!C->product->data, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Extra product struct not empty");
1066:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
1067:   PetscCallMPI(MPI_Comm_size(comm, &size));

1069:   /* create struct MatProductCtx_APMPI and attached it to C later */
1070:   PetscCall(PetscNew(&ptap));

1072:   /* get P_oth by taking rows of P (= non-zero cols of local A) from other processors */
1073:   PetscCall(MatGetBrowsOfAoCols_MPIAIJ_Private(A, P, MAT_INITIAL_MATRIX, C->structure_only, &ptap->startsj_s, &ptap->startsj_r, &ptap->bufa, &ptap->P_oth));

1075:   /* get P_loc by taking all local rows of P */
1076:   PetscCall(MatMPIAIJGetLocalMat_Private(P, MAT_INITIAL_MATRIX, C->structure_only, &ptap->P_loc));

1078:   p_loc  = (Mat_SeqAIJ *)ptap->P_loc->data;
1079:   pi_loc = p_loc->i;
1080:   pj_loc = p_loc->j;
1081:   if (size > 1) {
1082:     p_oth  = (Mat_SeqAIJ *)ptap->P_oth->data;
1083:     pi_oth = p_oth->i;
1084:     pj_oth = p_oth->j;
1085:   } else {
1086:     p_oth  = NULL;
1087:     pi_oth = NULL;
1088:     pj_oth = NULL;
1089:   }

1091:   /* first, compute symbolic AP = A_loc*P = A_diag*P_loc + A_off*P_oth */
1092:   PetscCall(PetscMalloc1(am + 1, &api));
1093:   ptap->api = api;
1094:   api[0]    = 0;

1096:   PetscCall(PetscLLCondensedCreate_Scalable(lsize, &lnk));

1098:   /* Initial FreeSpace size is fill*(nnz(A)+nnz(P)) */
1099:   PetscCall(PetscFreeSpaceGet(PetscRealIntMultTruncate(fill, PetscIntSumTruncate(adi[am], PetscIntSumTruncate(aoi[am], pi_loc[pm]))), &free_space));
1100:   current_space = free_space;
1101:   MatPreallocateBegin(comm, am, pn, dnz, onz);
1102:   for (i = 0; i < am; i++) {
1103:     /* diagonal portion of A */
1104:     nzi = adi[i + 1] - adi[i];
1105:     for (j = 0; j < nzi; j++) {
1106:       row  = *adj++;
1107:       pnz  = pi_loc[row + 1] - pi_loc[row];
1108:       Jptr = pj_loc + pi_loc[row];
1109:       /* Expand list if it is not long enough */
1110:       if (pnz + apnz_max > lsize) {
1111:         lsize = pnz + apnz_max;
1112:         PetscCall(PetscLLCondensedExpand_Scalable(lsize, &lnk));
1113:       }
1114:       /* add non-zero cols of P into the sorted linked list lnk */
1115:       PetscCall(PetscLLCondensedAddSorted_Scalable(pnz, Jptr, lnk));
1116:       apnz       = *lnk; /* The first element in the list is the number of items in the list */
1117:       api[i + 1] = api[i] + apnz;
1118:       if (apnz > apnz_max) apnz_max = apnz + 1; /* '1' for diagonal entry */
1119:     }
1120:     /* off-diagonal portion of A */
1121:     nzi = aoi[i + 1] - aoi[i];
1122:     for (j = 0; j < nzi; j++) {
1123:       row  = *aoj++;
1124:       pnz  = pi_oth[row + 1] - pi_oth[row];
1125:       Jptr = pj_oth + pi_oth[row];
1126:       /* Expand list if it is not long enough */
1127:       if (pnz + apnz_max > lsize) {
1128:         lsize = pnz + apnz_max;
1129:         PetscCall(PetscLLCondensedExpand_Scalable(lsize, &lnk));
1130:       }
1131:       /* add non-zero cols of P into the sorted linked list lnk */
1132:       PetscCall(PetscLLCondensedAddSorted_Scalable(pnz, Jptr, lnk));
1133:       apnz       = *lnk; /* The first element in the list is the number of items in the list */
1134:       api[i + 1] = api[i] + apnz;
1135:       if (apnz > apnz_max) apnz_max = apnz + 1; /* '1' for diagonal entry */
1136:     }

1138:     /* add missing diagonal entry */
1139:     if (C->force_diagonals) {
1140:       j = i + rstart; /* column index */
1141:       PetscCall(PetscLLCondensedAddSorted_Scalable(1, &j, lnk));
1142:     }

1144:     apnz       = *lnk;
1145:     api[i + 1] = api[i] + apnz;
1146:     if (apnz > apnz_max) apnz_max = apnz;

1148:     /* if free space is not available, double the total space in the list */
1149:     if (current_space->local_remaining < apnz) {
1150:       PetscCall(PetscFreeSpaceGet(PetscIntSumTruncate(apnz, current_space->total_array_size), &current_space));
1151:       nspacedouble++;
1152:     }

1154:     /* Copy data into free space, then initialize lnk */
1155:     PetscCall(PetscLLCondensedClean_Scalable(apnz, current_space->array, lnk));
1156:     PetscCall(MatPreallocateSet(i + rstart, apnz, current_space->array, dnz, onz));

1158:     current_space->array += apnz;
1159:     current_space->local_used += apnz;
1160:     current_space->local_remaining -= apnz;
1161:   }

1163:   /* Allocate space for apj, initialize apj, and */
1164:   /* destroy list of free space and other temporary array(s) */
1165:   PetscCall(PetscMalloc1(api[am], &ptap->apj));
1166:   apj = ptap->apj;
1167:   PetscCall(PetscFreeSpaceContiguous(&free_space, ptap->apj));
1168:   PetscCall(PetscLLCondensedDestroy_Scalable(lnk));

1170:   /* create and assemble symbolic parallel matrix C */
1171:   PetscCall(MatSetSizes(C, am, pn, PETSC_DETERMINE, PETSC_DETERMINE));
1172:   PetscCall(MatSetBlockSizesFromMats(C, A, P));
1173:   PetscCall(MatGetType(A, &mtype));
1174:   PetscCall(MatSetType(C, C->structure_only ? MATMPIAIJ : mtype));
1175:   PetscCall(MatMPIAIJSetPreallocation(C, 0, dnz, 0, onz));
1176:   MatPreallocateEnd(dnz, onz);

1178:   /* malloc apa for assembly C */
1179:   if (!C->structure_only) PetscCall(PetscCalloc1(apnz_max, &ptap->apa));

1181:   PetscCall(MatSetValues_MPIAIJ_CopyFromCSRFormat_Symbolic(C, apj, api));
1182:   C->nooffprocentries = PETSC_TRUE;
1183:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
1184:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
1185:   C->nooffprocentries = nooffprocentries;
1186:   PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));

1188:   C->ops->matmultnumeric = MatMatMultNumeric_MPIAIJ_MPIAIJ;
1189:   C->ops->productnumeric = MatProductNumeric_AB;

1191:   /* attach the supporting struct to C for reuse */
1192:   C->product->data    = ptap;
1193:   C->product->destroy = MatProductCtxDestroy_MPIAIJ_MatMatMult;

1195:   /* set MatInfo */
1196:   afill = (PetscReal)api[am] / (adi[am] + aoi[am] + pi_loc[pm] + 1) + 1.e-5;
1197:   if (afill < 1.0) afill = 1.0;
1198:   C->info.mallocs           = nspacedouble;
1199:   C->info.fill_ratio_given  = fill;
1200:   C->info.fill_ratio_needed = afill;

1202:   if (PetscDefined(USE_INFO)) {
1203:     if (api[am]) {
1204:       PetscCall(PetscInfo(C, "Reallocs %" PetscInt_FMT "; Fill ratio: given %g needed %g.\n", nspacedouble, (double)fill, (double)afill));
1205:       PetscCall(PetscInfo(C, "Use MatMatMult(A,B,MatReuse,%g,&C) for best performance.;\n", (double)afill));
1206:     } else PetscCall(PetscInfo(C, "Empty matrix product\n"));
1207:   }
1208:   PetscFunctionReturn(PETSC_SUCCESS);
1209: }

1211: /* This function is needed for the seqMPI matrix-matrix multiplication.  */
1212: /* Three input arrays are merged to one output array. The size of the    */
1213: /* output array is also output. Duplicate entries only show up once.     */
1214: static void Merge3SortedArrays(PetscInt size1, PetscInt *in1, PetscInt size2, PetscInt *in2, PetscInt size3, PetscInt *in3, PetscInt *size4, PetscInt *out)
1215: {
1216:   int i = 0, j = 0, k = 0, l = 0;

1218:   /* Traverse all three arrays */
1219:   while (i < size1 && j < size2 && k < size3) {
1220:     if (in1[i] < in2[j] && in1[i] < in3[k]) {
1221:       out[l++] = in1[i++];
1222:     } else if (in2[j] < in1[i] && in2[j] < in3[k]) {
1223:       out[l++] = in2[j++];
1224:     } else if (in3[k] < in1[i] && in3[k] < in2[j]) {
1225:       out[l++] = in3[k++];
1226:     } else if (in1[i] == in2[j] && in1[i] < in3[k]) {
1227:       out[l++] = in1[i];
1228:       i++, j++;
1229:     } else if (in1[i] == in3[k] && in1[i] < in2[j]) {
1230:       out[l++] = in1[i];
1231:       i++, k++;
1232:     } else if (in3[k] == in2[j] && in2[j] < in1[i]) {
1233:       out[l++] = in2[j];
1234:       k++, j++;
1235:     } else if (in1[i] == in2[j] && in1[i] == in3[k]) {
1236:       out[l++] = in1[i];
1237:       i++, j++, k++;
1238:     }
1239:   }

1241:   /* Traverse two remaining arrays */
1242:   while (i < size1 && j < size2) {
1243:     if (in1[i] < in2[j]) {
1244:       out[l++] = in1[i++];
1245:     } else if (in1[i] > in2[j]) {
1246:       out[l++] = in2[j++];
1247:     } else {
1248:       out[l++] = in1[i];
1249:       i++, j++;
1250:     }
1251:   }

1253:   while (i < size1 && k < size3) {
1254:     if (in1[i] < in3[k]) {
1255:       out[l++] = in1[i++];
1256:     } else if (in1[i] > in3[k]) {
1257:       out[l++] = in3[k++];
1258:     } else {
1259:       out[l++] = in1[i];
1260:       i++, k++;
1261:     }
1262:   }

1264:   while (k < size3 && j < size2) {
1265:     if (in3[k] < in2[j]) {
1266:       out[l++] = in3[k++];
1267:     } else if (in3[k] > in2[j]) {
1268:       out[l++] = in2[j++];
1269:     } else {
1270:       out[l++] = in3[k];
1271:       k++, j++;
1272:     }
1273:   }

1275:   /* Traverse one remaining array */
1276:   while (i < size1) out[l++] = in1[i++];
1277:   while (j < size2) out[l++] = in2[j++];
1278:   while (k < size3) out[l++] = in3[k++];

1280:   *size4 = l;
1281: }

1283: /* This matrix-matrix multiplication algorithm divides the multiplication into three multiplications and  */
1284: /* adds up the products. Two of these three multiplications are performed with existing (sequential)      */
1285: /* matrix-matrix multiplications.  */
1286: PetscErrorCode MatMatMultSymbolic_MPIAIJ_MPIAIJ_seqMPI(Mat A, Mat P, PetscReal fill, Mat C)
1287: {
1288:   MPI_Comm             comm;
1289:   PetscMPIInt          size;
1290:   MatProductCtx_APMPI *ptap;
1291:   PetscFreeSpaceList   free_space_diag = NULL, current_space = NULL;
1292:   Mat_MPIAIJ          *a  = (Mat_MPIAIJ *)A->data;
1293:   Mat_SeqAIJ          *ad = (Mat_SeqAIJ *)a->A->data, *ao = (Mat_SeqAIJ *)a->B->data, *p_loc;
1294:   Mat_MPIAIJ          *p = (Mat_MPIAIJ *)P->data;
1295:   Mat_SeqAIJ          *adpd_seq, *p_off, *aopoth_seq;
1296:   PetscInt             adponz, adpdnz;
1297:   PetscInt            *pi_loc, *dnz, *onz;
1298:   PetscInt            *adi = ad->i, *adj = ad->j, *aoi = ao->i, rstart = A->rmap->rstart;
1299:   PetscInt            *lnk, i, i1 = 0, pnz, row, *adpoi, *adpoj, *api, *adpoJ, *aopJ, *apJ, *Jptr, aopnz, nspacedouble = 0, j, nzi, *apj, apnz, *adpdi, *adpdj, *adpdJ, *poff_i, *poff_j, *j_temp, *aopothi, *aopothj;
1300:   PetscInt             am = A->rmap->n, pN = P->cmap->N, pn = P->cmap->n, pm = P->rmap->n, p_colstart, p_colend;
1301:   PetscBT              lnkbt;
1302:   PetscReal            afill;
1303:   PetscMPIInt          rank;
1304:   Mat                  adpd, aopoth;
1305:   MatType              mtype;
1306:   const char          *prefix;
1307:   const PetscBool      nooffprocentries = C->nooffprocentries;

1309:   PetscFunctionBegin;
1310:   MatCheckProduct(C, 4);
1311:   PetscCheck(!C->product->data, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Extra product struct not empty");
1312:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
1313:   PetscCallMPI(MPI_Comm_size(comm, &size));
1314:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
1315:   PetscCall(MatGetOwnershipRangeColumn(P, &p_colstart, &p_colend));

1317:   /* create struct MatProductCtx_APMPI and attached it to C later */
1318:   PetscCall(PetscNew(&ptap));

1320:   /* get P_oth by taking rows of P (= non-zero cols of local A) from other processors */
1321:   PetscCall(MatGetBrowsOfAoCols_MPIAIJ(A, P, MAT_INITIAL_MATRIX, &ptap->startsj_s, &ptap->startsj_r, &ptap->bufa, &ptap->P_oth));

1323:   /* get P_loc by taking all local rows of P */
1324:   PetscCall(MatMPIAIJGetLocalMat(P, MAT_INITIAL_MATRIX, &ptap->P_loc));

1326:   p_loc  = (Mat_SeqAIJ *)ptap->P_loc->data;
1327:   pi_loc = p_loc->i;

1329:   /* Allocate memory for the i arrays of the matrices A*P, A_diag*P_off and A_offd * P */
1330:   PetscCall(PetscMalloc1(am + 1, &api));
1331:   PetscCall(PetscMalloc1(am + 1, &adpoi));

1333:   adpoi[0]  = 0;
1334:   ptap->api = api;
1335:   api[0]    = 0;

1337:   /* create and initialize a linked list, will be used for both A_diag * P_loc_off and A_offd * P_oth */
1338:   PetscCall(PetscLLCondensedCreate(pN, pN, &lnk, &lnkbt));
1339:   MatPreallocateBegin(comm, am, pn, dnz, onz);

1341:   /* Symbolic calc of A_loc_diag * P_loc_diag */
1342:   PetscCall(MatGetOptionsPrefix(A, &prefix));
1343:   PetscCall(MatProductCreate(a->A, p->A, NULL, &adpd));
1344:   PetscCall(MatGetOptionsPrefix(A, &prefix));
1345:   PetscCall(MatSetOptionsPrefix(adpd, prefix));
1346:   PetscCall(MatAppendOptionsPrefix(adpd, "inner_diag_"));

1348:   PetscCall(MatProductSetType(adpd, MATPRODUCT_AB));
1349:   PetscCall(MatProductSetAlgorithm(adpd, "sorted"));
1350:   PetscCall(MatProductSetFill(adpd, fill));
1351:   PetscCall(MatProductSetFromOptions(adpd));

1353:   adpd->force_diagonals = C->force_diagonals;
1354:   PetscCall(MatProductSymbolic(adpd));

1356:   adpd_seq = (Mat_SeqAIJ *)adpd->data;
1357:   adpdi    = adpd_seq->i;
1358:   adpdj    = adpd_seq->j;
1359:   p_off    = (Mat_SeqAIJ *)p->B->data;
1360:   poff_i   = p_off->i;
1361:   poff_j   = p_off->j;

1363:   /* j_temp stores indices of a result row before they are added to the linked list */
1364:   PetscCall(PetscMalloc1(pN, &j_temp));

1366:   /* Symbolic calc of the A_diag * p_loc_off */
1367:   /* Initial FreeSpace size is fill*(nnz(A)+nnz(P)) */
1368:   PetscCall(PetscFreeSpaceGet(PetscRealIntMultTruncate(fill, PetscIntSumTruncate(adi[am], PetscIntSumTruncate(aoi[am], pi_loc[pm]))), &free_space_diag));
1369:   current_space = free_space_diag;

1371:   for (i = 0; i < am; i++) {
1372:     /* A_diag * P_loc_off */
1373:     nzi = adi[i + 1] - adi[i];
1374:     for (j = 0; j < nzi; j++) {
1375:       row  = *adj++;
1376:       pnz  = poff_i[row + 1] - poff_i[row];
1377:       Jptr = poff_j + poff_i[row];
1378:       for (i1 = 0; i1 < pnz; i1++) j_temp[i1] = p->garray[Jptr[i1]];
1379:       /* add non-zero cols of P into the sorted linked list lnk */
1380:       PetscCall(PetscLLCondensedAddSorted(pnz, j_temp, lnk, lnkbt));
1381:     }

1383:     adponz       = lnk[0];
1384:     adpoi[i + 1] = adpoi[i] + adponz;

1386:     /* if free space is not available, double the total space in the list */
1387:     if (current_space->local_remaining < adponz) {
1388:       PetscCall(PetscFreeSpaceGet(PetscIntSumTruncate(adponz, current_space->total_array_size), &current_space));
1389:       nspacedouble++;
1390:     }

1392:     /* Copy data into free space, then initialize lnk */
1393:     PetscCall(PetscLLCondensedClean(pN, adponz, current_space->array, lnk, lnkbt));

1395:     current_space->array += adponz;
1396:     current_space->local_used += adponz;
1397:     current_space->local_remaining -= adponz;
1398:   }

1400:   /* Symbolic calc of A_off * P_oth */
1401:   PetscCall(MatSetOptionsPrefix(a->B, prefix));
1402:   PetscCall(MatAppendOptionsPrefix(a->B, "inner_offdiag_"));
1403:   PetscCall(MatCreate(PETSC_COMM_SELF, &aopoth));
1404:   PetscCall(MatMatMultSymbolic_SeqAIJ_SeqAIJ(a->B, ptap->P_oth, fill, aopoth));
1405:   aopoth_seq = (Mat_SeqAIJ *)aopoth->data;
1406:   aopothi    = aopoth_seq->i;
1407:   aopothj    = aopoth_seq->j;

1409:   /* Allocate space for apj, adpj, aopj, ... */
1410:   /* destroy lists of free space and other temporary array(s) */

1412:   PetscCall(PetscMalloc1(aopothi[am] + adpoi[am] + adpdi[am], &ptap->apj));
1413:   PetscCall(PetscMalloc1(adpoi[am], &adpoj));

1415:   /* Copy from linked list to j-array */
1416:   PetscCall(PetscFreeSpaceContiguous(&free_space_diag, adpoj));
1417:   PetscCall(PetscLLDestroy(lnk, lnkbt));

1419:   adpoJ = adpoj;
1420:   adpdJ = adpdj;
1421:   aopJ  = aopothj;
1422:   apj   = ptap->apj;
1423:   apJ   = apj; /* still empty */

1425:   /* Merge j-arrays of A_off * P, A_diag * P_loc_off, and */
1426:   /* A_diag * P_loc_diag to get A*P */
1427:   for (i = 0; i < am; i++) {
1428:     aopnz  = aopothi[i + 1] - aopothi[i];
1429:     adponz = adpoi[i + 1] - adpoi[i];
1430:     adpdnz = adpdi[i + 1] - adpdi[i];

1432:     /* Correct indices from A_diag*P_diag */
1433:     for (i1 = 0; i1 < adpdnz; i1++) adpdJ[i1] += p_colstart;
1434:     /* Merge j-arrays of A_diag * P_loc_off and A_diag * P_loc_diag and A_off * P_oth */
1435:     Merge3SortedArrays(adponz, adpoJ, adpdnz, adpdJ, aopnz, aopJ, &apnz, apJ);
1436:     PetscCall(MatPreallocateSet(i + rstart, apnz, apJ, dnz, onz));

1438:     aopJ += aopnz;
1439:     adpoJ += adponz;
1440:     adpdJ += adpdnz;
1441:     apJ += apnz;
1442:     api[i + 1] = api[i] + apnz;
1443:   }

1445:   /* malloc apa to store dense row A[i,:]*P */
1446:   PetscCall(PetscCalloc1(pN, &ptap->apa));

1448:   /* create and assemble symbolic parallel matrix C */
1449:   PetscCall(MatSetSizes(C, am, pn, PETSC_DETERMINE, PETSC_DETERMINE));
1450:   PetscCall(MatSetBlockSizesFromMats(C, A, P));
1451:   PetscCall(MatGetType(A, &mtype));
1452:   PetscCall(MatSetType(C, mtype));
1453:   PetscCall(MatMPIAIJSetPreallocation(C, 0, dnz, 0, onz));
1454:   MatPreallocateEnd(dnz, onz);

1456:   PetscCall(MatSetValues_MPIAIJ_CopyFromCSRFormat_Symbolic(C, apj, api));
1457:   C->nooffprocentries = PETSC_TRUE;
1458:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
1459:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
1460:   C->nooffprocentries = nooffprocentries;
1461:   PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));

1463:   C->ops->matmultnumeric = MatMatMultNumeric_MPIAIJ_MPIAIJ_nonscalable;
1464:   C->ops->productnumeric = MatProductNumeric_AB;

1466:   /* attach the supporting struct to C for reuse */
1467:   C->product->data    = ptap;
1468:   C->product->destroy = MatProductCtxDestroy_MPIAIJ_MatMatMult;

1470:   /* set MatInfo */
1471:   afill = (PetscReal)api[am] / (adi[am] + aoi[am] + pi_loc[pm] + 1) + 1.e-5;
1472:   if (afill < 1.0) afill = 1.0;
1473:   C->info.mallocs           = nspacedouble;
1474:   C->info.fill_ratio_given  = fill;
1475:   C->info.fill_ratio_needed = afill;

1477:   if (PetscDefined(USE_INFO)) {
1478:     if (api[am]) {
1479:       PetscCall(PetscInfo(C, "Reallocs %" PetscInt_FMT "; Fill ratio: given %g needed %g.\n", nspacedouble, (double)fill, (double)afill));
1480:       PetscCall(PetscInfo(C, "Use MatMatMult(A,B,MatReuse,%g,&C) for best performance.;\n", (double)afill));
1481:     } else PetscCall(PetscInfo(C, "Empty matrix product\n"));
1482:   }

1484:   PetscCall(MatDestroy(&aopoth));
1485:   PetscCall(MatDestroy(&adpd));
1486:   PetscCall(PetscFree(j_temp));
1487:   PetscCall(PetscFree(adpoj));
1488:   PetscCall(PetscFree(adpoi));
1489:   PetscFunctionReturn(PETSC_SUCCESS);
1490: }

1492: /* This routine only works when scall=MAT_REUSE_MATRIX! */
1493: PetscErrorCode MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ_matmatmult(Mat P, Mat A, Mat C)
1494: {
1495:   MatProductCtx_APMPI *ptap;
1496:   Mat                  Pt;

1498:   PetscFunctionBegin;
1499:   MatCheckProduct(C, 3);
1500:   ptap = (MatProductCtx_APMPI *)C->product->data;
1501:   PetscCheck(ptap, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtAP cannot be computed. Missing data");
1502:   PetscCheck(ptap->Pt, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtA cannot be reused. Do not call MatProductClear()");

1504:   Pt = ptap->Pt;
1505:   PetscCall(MatTransposeSetPrecursor(P, Pt));
1506:   PetscCall(MatTranspose(P, MAT_REUSE_MATRIX, &Pt));
1507:   PetscCall(MatMatMultNumeric_MPIAIJ_MPIAIJ(Pt, A, C));
1508:   PetscFunctionReturn(PETSC_SUCCESS);
1509: }

1511: /* This routine is modified from MatPtAPSymbolic_MPIAIJ_MPIAIJ() */
1512: PetscErrorCode MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ_nonscalable(Mat P, Mat A, PetscReal fill, Mat C)
1513: {
1514:   MatProductCtx_APMPI     *ptap;
1515:   Mat_MPIAIJ              *p = (Mat_MPIAIJ *)P->data;
1516:   MPI_Comm                 comm;
1517:   PetscMPIInt              size, rank;
1518:   PetscFreeSpaceList       free_space = NULL, current_space = NULL;
1519:   PetscInt                 pn = P->cmap->n, aN = A->cmap->N, an = A->cmap->n;
1520:   PetscInt                *lnk, i, k, rstart;
1521:   PetscBT                  lnkbt;
1522:   PetscMPIInt              tagi, tagj, *len_si, *len_s, *len_ri, nrecv, proc, nsend;
1523:   PETSC_UNUSED PetscMPIInt icompleted = 0;
1524:   PetscInt               **buf_rj, **buf_ri, **buf_ri_k, row, ncols, *cols;
1525:   PetscInt                 len, *dnz, *onz, *owners, nzi;
1526:   PetscInt                 nrows, *buf_s, *buf_si, *buf_si_i, **nextrow, **nextci;
1527:   MPI_Request             *swaits, *rwaits;
1528:   MPI_Status              *sstatus, rstatus;
1529:   PetscLayout              rowmap;
1530:   PetscInt                *owners_co, *coi, *coj; /* i and j array of (p->B)^T*A*P - used in the communication */
1531:   PetscMPIInt             *len_r, *id_r;          /* array of length of comm->size, store send/recv matrix values */
1532:   PetscInt                *Jptr, *prmap = p->garray, con, j, Crmax;
1533:   Mat_SeqAIJ              *a_loc, *c_loc, *c_oth;
1534:   PetscHMapI               ta;
1535:   MatType                  mtype;
1536:   const char              *prefix;

1538:   PetscFunctionBegin;
1539:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
1540:   PetscCallMPI(MPI_Comm_size(comm, &size));
1541:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

1543:   /* create symbolic parallel matrix C */
1544:   PetscCall(MatGetType(A, &mtype));
1545:   PetscCall(MatSetType(C, mtype));

1547:   C->ops->transposematmultnumeric = MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ_nonscalable;

1549:   /* create struct MatProductCtx_APMPI and attached it to C later */
1550:   PetscCall(PetscNew(&ptap));

1552:   /* (0) compute Rd = Pd^T, Ro = Po^T  */
1553:   PetscCall(MatTranspose(p->A, MAT_INITIAL_MATRIX, &ptap->Rd));
1554:   PetscCall(MatTranspose(p->B, MAT_INITIAL_MATRIX, &ptap->Ro));

1556:   /* (1) compute symbolic A_loc */
1557:   PetscCall(MatMPIAIJGetLocalMat(A, MAT_INITIAL_MATRIX, &ptap->A_loc));

1559:   /* (2-1) compute symbolic C_oth = Ro*A_loc  */
1560:   PetscCall(MatGetOptionsPrefix(A, &prefix));
1561:   PetscCall(MatSetOptionsPrefix(ptap->Ro, prefix));
1562:   PetscCall(MatAppendOptionsPrefix(ptap->Ro, "inner_offdiag_"));
1563:   PetscCall(MatCreate(PETSC_COMM_SELF, &ptap->C_oth));
1564:   PetscCall(MatMatMultSymbolic_SeqAIJ_SeqAIJ(ptap->Ro, ptap->A_loc, fill, ptap->C_oth));

1566:   /* (3) send coj of C_oth to other processors  */
1567:   /* determine row ownership */
1568:   PetscCall(PetscLayoutCreate(comm, &rowmap));
1569:   rowmap->n  = pn;
1570:   rowmap->bs = 1;
1571:   PetscCall(PetscLayoutSetUp(rowmap));
1572:   owners = rowmap->range;

1574:   /* determine the number of messages to send, their lengths */
1575:   PetscCall(PetscMalloc4(size, &len_s, size, &len_si, size, &sstatus, size + 1, &owners_co));
1576:   PetscCall(PetscArrayzero(len_s, size));
1577:   PetscCall(PetscArrayzero(len_si, size));

1579:   c_oth = (Mat_SeqAIJ *)ptap->C_oth->data;
1580:   coi   = c_oth->i;
1581:   coj   = c_oth->j;
1582:   con   = ptap->C_oth->rmap->n;
1583:   proc  = 0;
1584:   for (i = 0; i < con; i++) {
1585:     while (prmap[i] >= owners[proc + 1]) proc++;
1586:     len_si[proc]++;                     /* num of rows in Co(=Pt*A) to be sent to [proc] */
1587:     len_s[proc] += coi[i + 1] - coi[i]; /* num of nonzeros in Co to be sent to [proc] */
1588:   }

1590:   len          = 0; /* max length of buf_si[], see (4) */
1591:   owners_co[0] = 0;
1592:   nsend        = 0;
1593:   for (proc = 0; proc < size; proc++) {
1594:     owners_co[proc + 1] = owners_co[proc] + len_si[proc];
1595:     if (len_s[proc]) {
1596:       nsend++;
1597:       len_si[proc] = 2 * (len_si[proc] + 1); /* length of buf_si to be sent to [proc] */
1598:       len += len_si[proc];
1599:     }
1600:   }

1602:   /* determine the number and length of messages to receive for coi and coj  */
1603:   PetscCall(PetscGatherNumberOfMessages(comm, NULL, len_s, &nrecv));
1604:   PetscCall(PetscGatherMessageLengths2(comm, nsend, nrecv, len_s, len_si, &id_r, &len_r, &len_ri));

1606:   /* post the Irecv and Isend of coj */
1607:   PetscCall(PetscCommGetNewTag(comm, &tagj));
1608:   PetscCall(PetscPostIrecvInt(comm, tagj, nrecv, id_r, len_r, &buf_rj, &rwaits));
1609:   PetscCall(PetscMalloc1(nsend, &swaits));
1610:   for (proc = 0, k = 0; proc < size; proc++) {
1611:     if (!len_s[proc]) continue;
1612:     i = owners_co[proc];
1613:     PetscCallMPI(MPIU_Isend(coj + coi[i], len_s[proc], MPIU_INT, proc, tagj, comm, swaits + k));
1614:     k++;
1615:   }

1617:   /* (2-2) compute symbolic C_loc = Rd*A_loc */
1618:   PetscCall(MatSetOptionsPrefix(ptap->Rd, prefix));
1619:   PetscCall(MatAppendOptionsPrefix(ptap->Rd, "inner_diag_"));
1620:   PetscCall(MatCreate(PETSC_COMM_SELF, &ptap->C_loc));
1621:   PetscCall(MatMatMultSymbolic_SeqAIJ_SeqAIJ(ptap->Rd, ptap->A_loc, fill, ptap->C_loc));
1622:   c_loc = (Mat_SeqAIJ *)ptap->C_loc->data;

1624:   /* receives coj are complete */
1625:   for (i = 0; i < nrecv; i++) PetscCallMPI(MPI_Waitany(nrecv, rwaits, &icompleted, &rstatus));
1626:   PetscCall(PetscFree(rwaits));
1627:   if (nsend) PetscCallMPI(MPI_Waitall(nsend, swaits, sstatus));

1629:   /* add received column indices into ta to update Crmax */
1630:   a_loc = (Mat_SeqAIJ *)ptap->A_loc->data;

1632:   /* create and initialize a linked list */
1633:   PetscCall(PetscHMapICreateWithSize(an, &ta)); /* for compute Crmax */
1634:   MatRowMergeMax_SeqAIJ(a_loc, ptap->A_loc->rmap->N, ta);

1636:   for (k = 0; k < nrecv; k++) { /* k-th received message */
1637:     Jptr = buf_rj[k];
1638:     for (j = 0; j < len_r[k]; j++) PetscCall(PetscHMapISet(ta, *(Jptr + j) + 1, 1));
1639:   }
1640:   PetscCall(PetscHMapIGetSize(ta, &Crmax));
1641:   PetscCall(PetscHMapIDestroy(&ta));

1643:   /* (4) send and recv coi */
1644:   PetscCall(PetscCommGetNewTag(comm, &tagi));
1645:   PetscCall(PetscPostIrecvInt(comm, tagi, nrecv, id_r, len_ri, &buf_ri, &rwaits));
1646:   PetscCall(PetscMalloc1(len, &buf_s));
1647:   buf_si = buf_s; /* points to the beginning of k-th msg to be sent */
1648:   for (proc = 0, k = 0; proc < size; proc++) {
1649:     if (!len_s[proc]) continue;
1650:     /* form outgoing message for i-structure:
1651:          buf_si[0]:                 nrows to be sent
1652:                [1:nrows]:           row index (global)
1653:                [nrows+1:2*nrows+1]: i-structure index
1654:     */
1655:     nrows       = len_si[proc] / 2 - 1; /* num of rows in Co to be sent to [proc] */
1656:     buf_si_i    = buf_si + nrows + 1;
1657:     buf_si[0]   = nrows;
1658:     buf_si_i[0] = 0;
1659:     nrows       = 0;
1660:     for (i = owners_co[proc]; i < owners_co[proc + 1]; i++) {
1661:       nzi                 = coi[i + 1] - coi[i];
1662:       buf_si_i[nrows + 1] = buf_si_i[nrows] + nzi;   /* i-structure */
1663:       buf_si[nrows + 1]   = prmap[i] - owners[proc]; /* local row index */
1664:       nrows++;
1665:     }
1666:     PetscCallMPI(MPIU_Isend(buf_si, len_si[proc], MPIU_INT, proc, tagi, comm, swaits + k));
1667:     k++;
1668:     buf_si += len_si[proc];
1669:   }
1670:   for (i = 0; i < nrecv; i++) PetscCallMPI(MPI_Waitany(nrecv, rwaits, &icompleted, &rstatus));
1671:   PetscCall(PetscFree(rwaits));
1672:   if (nsend) PetscCallMPI(MPI_Waitall(nsend, swaits, sstatus));

1674:   PetscCall(PetscFree4(len_s, len_si, sstatus, owners_co));
1675:   PetscCall(PetscFree(len_ri));
1676:   PetscCall(PetscFree(swaits));
1677:   PetscCall(PetscFree(buf_s));

1679:   /* (5) compute the local portion of C      */
1680:   /* set initial free space to be Crmax, sufficient for holding nonzeros in each row of C */
1681:   PetscCall(PetscFreeSpaceGet(Crmax, &free_space));
1682:   current_space = free_space;

1684:   PetscCall(PetscMalloc3(nrecv, &buf_ri_k, nrecv, &nextrow, nrecv, &nextci));
1685:   for (k = 0; k < nrecv; k++) {
1686:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
1687:     nrows       = *buf_ri_k[k];
1688:     nextrow[k]  = buf_ri_k[k] + 1;           /* next row number of k-th recved i-structure */
1689:     nextci[k]   = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th recved i-structure  */
1690:   }

1692:   MatPreallocateBegin(comm, pn, an, dnz, onz);
1693:   PetscCall(PetscLLCondensedCreate(Crmax, aN, &lnk, &lnkbt));
1694:   for (i = 0; i < pn; i++) { /* for each local row of C */
1695:     /* add C_loc into C */
1696:     nzi  = c_loc->i[i + 1] - c_loc->i[i];
1697:     Jptr = c_loc->j + c_loc->i[i];
1698:     PetscCall(PetscLLCondensedAddSorted(nzi, Jptr, lnk, lnkbt));

1700:     /* add received col data into lnk */
1701:     for (k = 0; k < nrecv; k++) { /* k-th received message */
1702:       if (i == *nextrow[k]) {     /* i-th row */
1703:         nzi  = *(nextci[k] + 1) - *nextci[k];
1704:         Jptr = buf_rj[k] + *nextci[k];
1705:         PetscCall(PetscLLCondensedAddSorted(nzi, Jptr, lnk, lnkbt));
1706:         nextrow[k]++;
1707:         nextci[k]++;
1708:       }
1709:     }

1711:     /* add missing diagonal entry */
1712:     if (C->force_diagonals) {
1713:       k = i + owners[rank]; /* column index */
1714:       PetscCall(PetscLLCondensedAddSorted(1, &k, lnk, lnkbt));
1715:     }

1717:     nzi = lnk[0];

1719:     /* copy data into free space, then initialize lnk */
1720:     PetscCall(PetscLLCondensedClean(aN, nzi, current_space->array, lnk, lnkbt));
1721:     PetscCall(MatPreallocateSet(i + owners[rank], nzi, current_space->array, dnz, onz));
1722:   }
1723:   PetscCall(PetscFree3(buf_ri_k, nextrow, nextci));
1724:   PetscCall(PetscLLDestroy(lnk, lnkbt));
1725:   PetscCall(PetscFreeSpaceDestroy(free_space));

1727:   /* local sizes and preallocation */
1728:   PetscCall(MatSetSizes(C, pn, an, PETSC_DETERMINE, PETSC_DETERMINE));
1729:   PetscCall(PetscLayoutSetBlockSize(C->rmap, P->cmap->bs));
1730:   PetscCall(PetscLayoutSetBlockSize(C->cmap, A->cmap->bs));
1731:   PetscCall(MatMPIAIJSetPreallocation(C, 0, dnz, 0, onz));
1732:   MatPreallocateEnd(dnz, onz);

1734:   /* add C_loc and C_oth to C */
1735:   PetscCall(MatGetOwnershipRange(C, &rstart, NULL));
1736:   for (i = 0; i < pn; i++) {
1737:     ncols = c_loc->i[i + 1] - c_loc->i[i];
1738:     cols  = c_loc->j + c_loc->i[i];
1739:     row   = rstart + i;
1740:     PetscCall(MatSetValues(C, 1, (const PetscInt *)&row, ncols, (const PetscInt *)cols, NULL, INSERT_VALUES));

1742:     if (C->force_diagonals) PetscCall(MatSetValues(C, 1, (const PetscInt *)&row, 1, (const PetscInt *)&row, NULL, INSERT_VALUES));
1743:   }
1744:   for (i = 0; i < con; i++) {
1745:     ncols = c_oth->i[i + 1] - c_oth->i[i];
1746:     cols  = c_oth->j + c_oth->i[i];
1747:     row   = prmap[i];
1748:     PetscCall(MatSetValues(C, 1, (const PetscInt *)&row, ncols, (const PetscInt *)cols, NULL, INSERT_VALUES));
1749:   }
1750:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
1751:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
1752:   PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));

1754:   /* members in merge */
1755:   PetscCall(PetscFree(id_r));
1756:   PetscCall(PetscFree(len_r));
1757:   PetscCall(PetscFree(buf_ri[0]));
1758:   PetscCall(PetscFree(buf_ri));
1759:   PetscCall(PetscFree(buf_rj[0]));
1760:   PetscCall(PetscFree(buf_rj));
1761:   PetscCall(PetscLayoutDestroy(&rowmap));

1763:   /* attach the supporting struct to C for reuse */
1764:   C->product->data    = ptap;
1765:   C->product->destroy = MatProductCtxDestroy_MPIAIJ_PtAP;
1766:   PetscFunctionReturn(PETSC_SUCCESS);
1767: }

1769: PetscErrorCode MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ_nonscalable(Mat P, Mat A, Mat C)
1770: {
1771:   Mat_MPIAIJ          *p = (Mat_MPIAIJ *)P->data;
1772:   Mat_SeqAIJ          *c_seq;
1773:   MatProductCtx_APMPI *ptap;
1774:   Mat                  A_loc, C_loc, C_oth;
1775:   PetscInt             i, rstart, rend, cm, ncols, row;
1776:   const PetscInt      *cols;
1777:   const PetscScalar   *vals;

1779:   PetscFunctionBegin;
1780:   MatCheckProduct(C, 3);
1781:   ptap = (MatProductCtx_APMPI *)C->product->data;
1782:   PetscCheck(ptap, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtAP cannot be computed. Missing data");
1783:   PetscCheck(ptap->A_loc, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtA cannot be reused. Do not call MatProductClear()");
1784:   PetscCall(MatZeroEntries(C));

1786:   /* These matrices are obtained in MatTransposeMatMultSymbolic() */
1787:   /* 1) get R = Pd^T, Ro = Po^T */
1788:   PetscCall(MatTransposeSetPrecursor(p->A, ptap->Rd));
1789:   PetscCall(MatTranspose(p->A, MAT_REUSE_MATRIX, &ptap->Rd));
1790:   PetscCall(MatTransposeSetPrecursor(p->B, ptap->Ro));
1791:   PetscCall(MatTranspose(p->B, MAT_REUSE_MATRIX, &ptap->Ro));

1793:   /* 2) compute numeric A_loc */
1794:   PetscCall(MatMPIAIJGetLocalMat(A, MAT_REUSE_MATRIX, &ptap->A_loc));

1796:   /* 3) C_loc = Rd*A_loc, C_oth = Ro*A_loc */
1797:   A_loc = ptap->A_loc;
1798:   PetscCall(ptap->C_loc->ops->matmultnumeric(ptap->Rd, A_loc, ptap->C_loc));
1799:   PetscCall(ptap->C_oth->ops->matmultnumeric(ptap->Ro, A_loc, ptap->C_oth));
1800:   C_loc = ptap->C_loc;
1801:   C_oth = ptap->C_oth;

1803:   /* add C_loc and C_oth to C */
1804:   PetscCall(MatGetOwnershipRange(C, &rstart, &rend));

1806:   /* C_loc -> C */
1807:   cm    = C_loc->rmap->N;
1808:   c_seq = (Mat_SeqAIJ *)C_loc->data;
1809:   cols  = c_seq->j;
1810:   vals  = c_seq->a;
1811:   for (i = 0; i < cm; i++) {
1812:     ncols = c_seq->i[i + 1] - c_seq->i[i];
1813:     row   = rstart + i;
1814:     PetscCall(MatSetValues(C, 1, &row, ncols, cols, vals, ADD_VALUES));
1815:     cols += ncols;
1816:     vals += ncols;
1817:   }

1819:   /* Co -> C, off-processor part */
1820:   cm    = C_oth->rmap->N;
1821:   c_seq = (Mat_SeqAIJ *)C_oth->data;
1822:   cols  = c_seq->j;
1823:   vals  = c_seq->a;
1824:   for (i = 0; i < cm; i++) {
1825:     ncols = c_seq->i[i + 1] - c_seq->i[i];
1826:     row   = p->garray[i];
1827:     PetscCall(MatSetValues(C, 1, &row, ncols, cols, vals, ADD_VALUES));
1828:     cols += ncols;
1829:     vals += ncols;
1830:   }
1831:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
1832:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
1833:   PetscFunctionReturn(PETSC_SUCCESS);
1834: }

1836: PetscErrorCode MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ(Mat P, Mat A, Mat C)
1837: {
1838:   MatMergeSeqsToMPI   *merge;
1839:   Mat_MPIAIJ          *p  = (Mat_MPIAIJ *)P->data;
1840:   Mat_SeqAIJ          *pd = (Mat_SeqAIJ *)p->A->data, *po = (Mat_SeqAIJ *)p->B->data;
1841:   MatProductCtx_APMPI *ap;
1842:   PetscInt            *adj;
1843:   PetscInt             i, j, k, anz, pnz, row, *cj, nexta;
1844:   MatScalar           *ada, *ca, valtmp;
1845:   PetscInt             am = A->rmap->n, cm = C->rmap->n, pon = p->B->cmap->n;
1846:   MPI_Comm             comm;
1847:   PetscMPIInt          size, rank, taga, *len_s, proc;
1848:   PetscInt            *owners, nrows, **buf_ri_k, **nextrow, **nextci;
1849:   PetscInt           **buf_ri, **buf_rj;
1850:   PetscInt             cnz = 0, *bj_i, *bi, *bj, bnz, nextcj; /* bi,bj,ba: local array of C(mpi mat) */
1851:   MPI_Request         *s_waits, *r_waits;
1852:   MPI_Status          *status;
1853:   MatScalar          **abuf_r, *ba_i, *pA, *coa, *ba;
1854:   const PetscScalar   *dummy;
1855:   PetscInt            *ai, *aj, *coi, *coj, *poJ, *pdJ;
1856:   Mat                  A_loc;
1857:   Mat_SeqAIJ          *a_loc;
1858:   const PetscBool      nooffprocentries = C->nooffprocentries;

1860:   PetscFunctionBegin;
1861:   MatCheckProduct(C, 3);
1862:   ap = (MatProductCtx_APMPI *)C->product->data;
1863:   PetscCheck(ap, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtA cannot be computed. Missing data");
1864:   PetscCheck(ap->A_loc, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONGSTATE, "PtA cannot be reused. Do not call MatProductClear()");
1865:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
1866:   PetscCallMPI(MPI_Comm_size(comm, &size));
1867:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

1869:   merge = ap->merge;

1871:   /* 2) compute numeric C_seq = P_loc^T*A_loc */
1872:   /* get data from symbolic products */
1873:   coi = merge->coi;
1874:   coj = merge->coj;
1875:   PetscCall(PetscCalloc1(coi[pon], &coa));
1876:   bi     = merge->bi;
1877:   bj     = merge->bj;
1878:   owners = merge->rowmap->range;
1879:   PetscCall(PetscCalloc1(bi[cm], &ba));

1881:   /* get A_loc by taking all local rows of A */
1882:   A_loc = ap->A_loc;
1883:   PetscCall(MatMPIAIJGetLocalMat(A, MAT_REUSE_MATRIX, &A_loc));
1884:   a_loc = (Mat_SeqAIJ *)A_loc->data;
1885:   ai    = a_loc->i;
1886:   aj    = a_loc->j;

1888:   /* trigger copy to CPU */
1889:   PetscCall(MatSeqAIJGetArrayRead(p->A, &dummy));
1890:   PetscCall(MatSeqAIJRestoreArrayRead(p->A, &dummy));
1891:   PetscCall(MatSeqAIJGetArrayRead(p->B, &dummy));
1892:   PetscCall(MatSeqAIJRestoreArrayRead(p->B, &dummy));
1893:   for (i = 0; i < am; i++) {
1894:     anz = ai[i + 1] - ai[i];
1895:     adj = aj + ai[i];
1896:     ada = a_loc->a + ai[i];

1898:     /* 2-b) Compute Cseq = P_loc[i,:]^T*A[i,:] using outer product */
1899:     /* put the value into Co=(p->B)^T*A (off-diagonal part, send to others) */
1900:     pnz = po->i[i + 1] - po->i[i];
1901:     poJ = po->j + po->i[i];
1902:     pA  = po->a + po->i[i];
1903:     for (j = 0; j < pnz; j++) {
1904:       row = poJ[j];
1905:       cj  = coj + coi[row];
1906:       ca  = coa + coi[row];
1907:       /* perform sparse axpy */
1908:       nexta  = 0;
1909:       valtmp = pA[j];
1910:       for (k = 0; nexta < anz; k++) {
1911:         if (cj[k] == adj[nexta]) {
1912:           ca[k] += valtmp * ada[nexta];
1913:           nexta++;
1914:         }
1915:       }
1916:       PetscCall(PetscLogFlops(2.0 * anz));
1917:     }

1919:     /* put the value into Cd (diagonal part) */
1920:     pnz = pd->i[i + 1] - pd->i[i];
1921:     pdJ = pd->j + pd->i[i];
1922:     pA  = pd->a + pd->i[i];
1923:     for (j = 0; j < pnz; j++) {
1924:       row = pdJ[j];
1925:       cj  = bj + bi[row];
1926:       ca  = ba + bi[row];
1927:       /* perform sparse axpy */
1928:       nexta  = 0;
1929:       valtmp = pA[j];
1930:       for (k = 0; nexta < anz; k++) {
1931:         if (cj[k] == adj[nexta]) {
1932:           ca[k] += valtmp * ada[nexta];
1933:           nexta++;
1934:         }
1935:       }
1936:       PetscCall(PetscLogFlops(2.0 * anz));
1937:     }
1938:   }

1940:   /* 3) send and recv matrix values coa */
1941:   buf_ri = merge->buf_ri;
1942:   buf_rj = merge->buf_rj;
1943:   len_s  = merge->len_s;
1944:   PetscCall(PetscCommGetNewTag(comm, &taga));
1945:   PetscCall(PetscPostIrecvScalar(comm, taga, merge->nrecv, merge->id_r, merge->len_r, &abuf_r, &r_waits));

1947:   PetscCall(PetscMalloc2(merge->nsend, &s_waits, size, &status));
1948:   for (proc = 0, k = 0; proc < size; proc++) {
1949:     if (!len_s[proc]) continue;
1950:     i = merge->owners_co[proc];
1951:     PetscCallMPI(MPIU_Isend(coa + coi[i], len_s[proc], MPIU_MATSCALAR, proc, taga, comm, s_waits + k));
1952:     k++;
1953:   }
1954:   if (merge->nrecv) PetscCallMPI(MPI_Waitall(merge->nrecv, r_waits, status));
1955:   if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, s_waits, status));

1957:   PetscCall(PetscFree2(s_waits, status));
1958:   PetscCall(PetscFree(r_waits));
1959:   PetscCall(PetscFree(coa));

1961:   /* 4) insert local Cseq and received values into Cmpi */
1962:   PetscCall(PetscMalloc3(merge->nrecv, &buf_ri_k, merge->nrecv, &nextrow, merge->nrecv, &nextci));
1963:   for (k = 0; k < merge->nrecv; k++) {
1964:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
1965:     nrows       = *buf_ri_k[k];
1966:     nextrow[k]  = buf_ri_k[k] + 1;           /* next row number of k-th recved i-structure */
1967:     nextci[k]   = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th recved i-structure  */
1968:   }

1970:   for (i = 0; i < cm; i++) {
1971:     row  = owners[rank] + i; /* global row index of C_seq */
1972:     bj_i = bj + bi[i];       /* col indices of the i-th row of C */
1973:     ba_i = ba + bi[i];
1974:     bnz  = bi[i + 1] - bi[i];
1975:     /* add received vals into ba */
1976:     for (k = 0; k < merge->nrecv; k++) { /* k-th received message */
1977:       /* i-th row */
1978:       if (i == *nextrow[k]) {
1979:         cnz    = *(nextci[k] + 1) - *nextci[k];
1980:         cj     = buf_rj[k] + *nextci[k];
1981:         ca     = abuf_r[k] + *nextci[k];
1982:         nextcj = 0;
1983:         for (j = 0; nextcj < cnz; j++) {
1984:           if (bj_i[j] == cj[nextcj]) { /* bcol == ccol */
1985:             ba_i[j] += ca[nextcj++];
1986:           }
1987:         }
1988:         nextrow[k]++;
1989:         nextci[k]++;
1990:         PetscCall(PetscLogFlops(2.0 * cnz));
1991:       }
1992:     }
1993:     PetscCall(MatSetValues(C, 1, &row, bnz, bj_i, ba_i, INSERT_VALUES));
1994:   }
1995:   C->nooffprocentries = PETSC_TRUE;
1996:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
1997:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
1998:   C->nooffprocentries = nooffprocentries;

2000:   PetscCall(PetscFree(ba));
2001:   PetscCall(PetscFree(abuf_r[0]));
2002:   PetscCall(PetscFree(abuf_r));
2003:   PetscCall(PetscFree3(buf_ri_k, nextrow, nextci));
2004:   PetscFunctionReturn(PETSC_SUCCESS);
2005: }

2007: PetscErrorCode MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ(Mat P, Mat A, PetscReal fill, Mat C)
2008: {
2009:   Mat                  A_loc;
2010:   MatProductCtx_APMPI *ap;
2011:   PetscFreeSpaceList   free_space = NULL, current_space = NULL;
2012:   Mat_MPIAIJ          *p = (Mat_MPIAIJ *)P->data, *a = (Mat_MPIAIJ *)A->data;
2013:   PetscInt            *pdti, *pdtj, *poti, *potj, *ptJ;
2014:   PetscInt             nnz;
2015:   PetscInt            *lnk, *owners_co, *coi, *coj, i, k, pnz, row;
2016:   PetscInt             am = A->rmap->n, pn = P->cmap->n;
2017:   MPI_Comm             comm;
2018:   PetscMPIInt          size, rank, tagi, tagj, *len_si, *len_s, *len_ri, proc;
2019:   PetscInt           **buf_rj, **buf_ri, **buf_ri_k;
2020:   PetscInt             len, *dnz, *onz, *owners;
2021:   PetscInt             nzi, *bi, *bj;
2022:   PetscInt             nrows, *buf_s, *buf_si, *buf_si_i, **nextrow, **nextci;
2023:   MPI_Request         *swaits, *rwaits;
2024:   MPI_Status          *sstatus, rstatus;
2025:   MatMergeSeqsToMPI   *merge;
2026:   PetscInt            *ai, *aj, *Jptr, anz, *prmap = p->garray, pon, nspacedouble = 0, j;
2027:   PetscReal            afill  = 1.0, afill_tmp;
2028:   PetscInt             rstart = P->cmap->rstart, rmax, Armax;
2029:   Mat_SeqAIJ          *a_loc;
2030:   PetscHMapI           ta;
2031:   MatType              mtype;
2032:   const PetscBool      nooffprocentries = C->nooffprocentries;

2034:   PetscFunctionBegin;
2035:   PetscCall(PetscObjectGetComm((PetscObject)A, &comm));
2036:   /* check if matrix local sizes are compatible */
2037:   PetscCheck(A->rmap->rstart == P->rmap->rstart && A->rmap->rend == P->rmap->rend, comm, PETSC_ERR_ARG_SIZ, "Matrix local dimensions are incompatible, A (%" PetscInt_FMT ", %" PetscInt_FMT ") != P (%" PetscInt_FMT ",%" PetscInt_FMT ")", A->rmap->rstart,
2038:              A->rmap->rend, P->rmap->rstart, P->rmap->rend);

2040:   PetscCallMPI(MPI_Comm_size(comm, &size));
2041:   PetscCallMPI(MPI_Comm_rank(comm, &rank));

2043:   /* create struct MatProductCtx_APMPI and attached it to C later */
2044:   PetscCall(PetscNew(&ap));

2046:   /* get A_loc by taking all local rows of A */
2047:   PetscCall(MatMPIAIJGetLocalMat_Private(A, MAT_INITIAL_MATRIX, C->structure_only, &A_loc));

2049:   ap->A_loc = A_loc;
2050:   a_loc     = (Mat_SeqAIJ *)A_loc->data;
2051:   ai        = a_loc->i;
2052:   aj        = a_loc->j;

2054:   /* determine symbolic Co=(p->B)^T*A - send to others */
2055:   PetscCall(MatGetSymbolicTranspose_SeqAIJ(p->A, &pdti, &pdtj));
2056:   PetscCall(MatGetSymbolicTranspose_SeqAIJ(p->B, &poti, &potj));
2057:   pon = p->B->cmap->n; /* total num of rows to be sent to other processors
2058:                          >= (num of nonzero rows of C_seq) - pn */
2059:   PetscCall(PetscMalloc1(pon + 1, &coi));
2060:   coi[0] = 0;

2062:   /* set initial free space to be fill*(nnz(p->B) + nnz(A)) */
2063:   nnz = PetscRealIntMultTruncate(fill, PetscIntSumTruncate(poti[pon], ai[am]));
2064:   PetscCall(PetscFreeSpaceGet(nnz, &free_space));
2065:   current_space = free_space;

2067:   /* create and initialize a linked list */
2068:   PetscCall(PetscHMapICreateWithSize(A->cmap->n + a->B->cmap->N, &ta));
2069:   MatRowMergeMax_SeqAIJ(a_loc, am, ta);
2070:   PetscCall(PetscHMapIGetSize(ta, &Armax));

2072:   PetscCall(PetscLLCondensedCreate_Scalable(Armax, &lnk));

2074:   for (i = 0; i < pon; i++) {
2075:     pnz = poti[i + 1] - poti[i];
2076:     ptJ = potj + poti[i];
2077:     for (j = 0; j < pnz; j++) {
2078:       row  = ptJ[j]; /* row of A_loc == col of Pot */
2079:       anz  = ai[row + 1] - ai[row];
2080:       Jptr = aj + ai[row];
2081:       /* add non-zero cols of AP into the sorted linked list lnk */
2082:       PetscCall(PetscLLCondensedAddSorted_Scalable(anz, Jptr, lnk));
2083:     }
2084:     nnz = lnk[0];

2086:     /* If free space is not available, double the total space in the list */
2087:     if (current_space->local_remaining < nnz) {
2088:       PetscCall(PetscFreeSpaceGet(PetscIntSumTruncate(nnz, current_space->total_array_size), &current_space));
2089:       nspacedouble++;
2090:     }

2092:     /* Copy data into free space, and zero out denserows */
2093:     PetscCall(PetscLLCondensedClean_Scalable(nnz, current_space->array, lnk));

2095:     current_space->array += nnz;
2096:     current_space->local_used += nnz;
2097:     current_space->local_remaining -= nnz;

2099:     coi[i + 1] = coi[i] + nnz;
2100:   }

2102:   PetscCall(PetscMalloc1(coi[pon], &coj));
2103:   PetscCall(PetscFreeSpaceContiguous(&free_space, coj));
2104:   PetscCall(PetscLLCondensedDestroy_Scalable(lnk)); /* must destroy to get a new one for C */

2106:   afill_tmp = (PetscReal)coi[pon] / (poti[pon] + ai[am] + 1);
2107:   if (afill_tmp > afill) afill = afill_tmp;

2109:   /* send j-array (coj) of Co to other processors */
2110:   /* determine row ownership */
2111:   PetscCall(PetscNew(&merge));
2112:   PetscCall(PetscLayoutCreate(comm, &merge->rowmap));

2114:   merge->rowmap->n  = pn;
2115:   merge->rowmap->bs = 1;

2117:   PetscCall(PetscLayoutSetUp(merge->rowmap));
2118:   owners = merge->rowmap->range;

2120:   /* determine the number of messages to send, their lengths */
2121:   PetscCall(PetscCalloc1(size, &len_si));
2122:   PetscCall(PetscCalloc1(size, &merge->len_s));

2124:   len_s        = merge->len_s;
2125:   merge->nsend = 0;

2127:   PetscCall(PetscMalloc1(size + 1, &owners_co));

2129:   proc = 0;
2130:   for (i = 0; i < pon; i++) {
2131:     while (prmap[i] >= owners[proc + 1]) proc++;
2132:     len_si[proc]++; /* num of rows in Co to be sent to [proc] */
2133:     len_s[proc] += coi[i + 1] - coi[i];
2134:   }

2136:   len          = 0; /* max length of buf_si[] */
2137:   owners_co[0] = 0;
2138:   for (proc = 0; proc < size; proc++) {
2139:     owners_co[proc + 1] = owners_co[proc] + len_si[proc];
2140:     if (len_s[proc]) {
2141:       merge->nsend++;
2142:       len_si[proc] = 2 * (len_si[proc] + 1);
2143:       len += len_si[proc];
2144:     }
2145:   }

2147:   /* determine the number and length of messages to receive for coi and coj  */
2148:   PetscCall(PetscGatherNumberOfMessages(comm, NULL, len_s, &merge->nrecv));
2149:   PetscCall(PetscGatherMessageLengths2(comm, merge->nsend, merge->nrecv, len_s, len_si, &merge->id_r, &merge->len_r, &len_ri));

2151:   /* post the Irecv and Isend of coj */
2152:   PetscCall(PetscCommGetNewTag(comm, &tagj));
2153:   PetscCall(PetscPostIrecvInt(comm, tagj, merge->nrecv, merge->id_r, merge->len_r, &buf_rj, &rwaits));
2154:   PetscCall(PetscMalloc1(merge->nsend, &swaits));
2155:   for (proc = 0, k = 0; proc < size; proc++) {
2156:     if (!len_s[proc]) continue;
2157:     i = owners_co[proc];
2158:     PetscCallMPI(MPIU_Isend(coj + coi[i], len_s[proc], MPIU_INT, proc, tagj, comm, swaits + k));
2159:     k++;
2160:   }

2162:   /* receives and sends of coj are complete */
2163:   PetscCall(PetscMalloc1(size, &sstatus));
2164:   for (i = 0; i < merge->nrecv; i++) {
2165:     PETSC_UNUSED PetscMPIInt icompleted;
2166:     PetscCallMPI(MPI_Waitany(merge->nrecv, rwaits, &icompleted, &rstatus));
2167:   }
2168:   PetscCall(PetscFree(rwaits));
2169:   if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, swaits, sstatus));

2171:   /* add received column indices into table to update Armax */
2172:   /* Armax can be as large as aN if a P[row,:] is dense, see src/ksp/ksp/tutorials/ex56.c! */
2173:   for (k = 0; k < merge->nrecv; k++) { /* k-th received message */
2174:     Jptr = buf_rj[k];
2175:     for (j = 0; j < merge->len_r[k]; j++) PetscCall(PetscHMapISet(ta, *(Jptr + j) + 1, 1));
2176:   }
2177:   PetscCall(PetscHMapIGetSize(ta, &Armax));

2179:   /* send and recv coi */
2180:   PetscCall(PetscCommGetNewTag(comm, &tagi));
2181:   PetscCall(PetscPostIrecvInt(comm, tagi, merge->nrecv, merge->id_r, len_ri, &buf_ri, &rwaits));
2182:   PetscCall(PetscMalloc1(len, &buf_s));
2183:   buf_si = buf_s; /* points to the beginning of k-th msg to be sent */
2184:   for (proc = 0, k = 0; proc < size; proc++) {
2185:     if (!len_s[proc]) continue;
2186:     /* form outgoing message for i-structure:
2187:          buf_si[0]:                 nrows to be sent
2188:                [1:nrows]:           row index (global)
2189:                [nrows+1:2*nrows+1]: i-structure index
2190:     */
2191:     nrows       = len_si[proc] / 2 - 1;
2192:     buf_si_i    = buf_si + nrows + 1;
2193:     buf_si[0]   = nrows;
2194:     buf_si_i[0] = 0;
2195:     nrows       = 0;
2196:     for (i = owners_co[proc]; i < owners_co[proc + 1]; i++) {
2197:       nzi                 = coi[i + 1] - coi[i];
2198:       buf_si_i[nrows + 1] = buf_si_i[nrows] + nzi;   /* i-structure */
2199:       buf_si[nrows + 1]   = prmap[i] - owners[proc]; /* local row index */
2200:       nrows++;
2201:     }
2202:     PetscCallMPI(MPIU_Isend(buf_si, len_si[proc], MPIU_INT, proc, tagi, comm, swaits + k));
2203:     k++;
2204:     buf_si += len_si[proc];
2205:   }
2206:   i = merge->nrecv;
2207:   while (i--) {
2208:     PETSC_UNUSED PetscMPIInt icompleted;
2209:     PetscCallMPI(MPI_Waitany(merge->nrecv, rwaits, &icompleted, &rstatus));
2210:   }
2211:   PetscCall(PetscFree(rwaits));
2212:   if (merge->nsend) PetscCallMPI(MPI_Waitall(merge->nsend, swaits, sstatus));
2213:   PetscCall(PetscFree(len_si));
2214:   PetscCall(PetscFree(len_ri));
2215:   PetscCall(PetscFree(swaits));
2216:   PetscCall(PetscFree(sstatus));
2217:   PetscCall(PetscFree(buf_s));

2219:   /* compute the local portion of C (mpi mat) */
2220:   /* allocate bi array and free space for accumulating nonzero column info */
2221:   PetscCall(PetscMalloc1(pn + 1, &bi));
2222:   bi[0] = 0;

2224:   /* set initial free space to be fill*(nnz(P) + nnz(AP)) */
2225:   nnz = PetscRealIntMultTruncate(fill, PetscIntSumTruncate(pdti[pn], PetscIntSumTruncate(poti[pon], ai[am])));
2226:   PetscCall(PetscFreeSpaceGet(nnz, &free_space));
2227:   current_space = free_space;

2229:   PetscCall(PetscMalloc3(merge->nrecv, &buf_ri_k, merge->nrecv, &nextrow, merge->nrecv, &nextci));
2230:   for (k = 0; k < merge->nrecv; k++) {
2231:     buf_ri_k[k] = buf_ri[k]; /* beginning of k-th recved i-structure */
2232:     nrows       = *buf_ri_k[k];
2233:     nextrow[k]  = buf_ri_k[k] + 1;           /* next row number of k-th recved i-structure */
2234:     nextci[k]   = buf_ri_k[k] + (nrows + 1); /* points to the next i-structure of k-th received i-structure  */
2235:   }

2237:   PetscCall(PetscLLCondensedCreate_Scalable(Armax, &lnk));
2238:   MatPreallocateBegin(comm, pn, A->cmap->n, dnz, onz);
2239:   rmax = 0;
2240:   for (i = 0; i < pn; i++) {
2241:     /* add pdt[i,:]*AP into lnk */
2242:     pnz = pdti[i + 1] - pdti[i];
2243:     ptJ = pdtj + pdti[i];
2244:     for (j = 0; j < pnz; j++) {
2245:       row  = ptJ[j]; /* row of AP == col of Pt */
2246:       anz  = ai[row + 1] - ai[row];
2247:       Jptr = aj + ai[row];
2248:       /* add non-zero cols of AP into the sorted linked list lnk */
2249:       PetscCall(PetscLLCondensedAddSorted_Scalable(anz, Jptr, lnk));
2250:     }

2252:     /* add received col data into lnk */
2253:     for (k = 0; k < merge->nrecv; k++) { /* k-th received message */
2254:       if (i == *nextrow[k]) {            /* i-th row */
2255:         nzi  = *(nextci[k] + 1) - *nextci[k];
2256:         Jptr = buf_rj[k] + *nextci[k];
2257:         PetscCall(PetscLLCondensedAddSorted_Scalable(nzi, Jptr, lnk));
2258:         nextrow[k]++;
2259:         nextci[k]++;
2260:       }
2261:     }

2263:     /* add missing diagonal entry */
2264:     if (C->force_diagonals) {
2265:       k = i + owners[rank]; /* column index */
2266:       PetscCall(PetscLLCondensedAddSorted_Scalable(1, &k, lnk));
2267:     }

2269:     nnz = lnk[0];

2271:     /* if free space is not available, make more free space */
2272:     if (current_space->local_remaining < nnz) {
2273:       PetscCall(PetscFreeSpaceGet(PetscIntSumTruncate(nnz, current_space->total_array_size), &current_space));
2274:       nspacedouble++;
2275:     }
2276:     /* copy data into free space, then initialize lnk */
2277:     PetscCall(PetscLLCondensedClean_Scalable(nnz, current_space->array, lnk));
2278:     PetscCall(MatPreallocateSet(i + owners[rank], nnz, current_space->array, dnz, onz));

2280:     current_space->array += nnz;
2281:     current_space->local_used += nnz;
2282:     current_space->local_remaining -= nnz;

2284:     bi[i + 1] = bi[i] + nnz;
2285:     if (nnz > rmax) rmax = nnz;
2286:   }
2287:   PetscCall(PetscFree3(buf_ri_k, nextrow, nextci));

2289:   PetscCall(PetscMalloc1(bi[pn], &bj));
2290:   PetscCall(PetscFreeSpaceContiguous(&free_space, bj));
2291:   afill_tmp = (PetscReal)bi[pn] / (pdti[pn] + poti[pon] + ai[am] + 1);
2292:   if (afill_tmp > afill) afill = afill_tmp;
2293:   PetscCall(PetscLLCondensedDestroy_Scalable(lnk));
2294:   PetscCall(PetscHMapIDestroy(&ta));
2295:   PetscCall(MatRestoreSymbolicTranspose_SeqAIJ(p->A, &pdti, &pdtj));
2296:   PetscCall(MatRestoreSymbolicTranspose_SeqAIJ(p->B, &poti, &potj));

2298:   /* create symbolic parallel matrix C - why cannot be assembled in Numeric part   */
2299:   PetscCall(MatSetSizes(C, pn, A->cmap->n, PETSC_DETERMINE, PETSC_DETERMINE));
2300:   PetscCall(MatSetBlockSizes(C, P->cmap->bs, A->cmap->bs));
2301:   PetscCall(MatGetType(A, &mtype));
2302:   PetscCall(MatSetType(C, C->structure_only ? MATMPIAIJ : mtype));
2303:   PetscCall(MatMPIAIJSetPreallocation(C, 0, dnz, 0, onz));
2304:   MatPreallocateEnd(dnz, onz);
2305:   PetscCall(MatSetBlockSize(C, 1));
2306:   for (i = 0; i < pn; i++) {
2307:     row  = i + rstart;
2308:     nnz  = bi[i + 1] - bi[i];
2309:     Jptr = bj + bi[i];
2310:     PetscCall(MatSetValues(C, 1, &row, nnz, Jptr, NULL, INSERT_VALUES));
2311:   }
2312:   C->nooffprocentries = PETSC_TRUE;
2313:   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
2314:   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
2315:   C->nooffprocentries = nooffprocentries;
2316:   PetscCall(MatSetOption(C, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
2317:   merge->bi        = bi;
2318:   merge->bj        = bj;
2319:   merge->coi       = coi;
2320:   merge->coj       = coj;
2321:   merge->buf_ri    = buf_ri;
2322:   merge->buf_rj    = buf_rj;
2323:   merge->owners_co = owners_co;

2325:   /* attach the supporting struct to C for reuse */
2326:   C->product->data    = ap;
2327:   C->product->destroy = MatProductCtxDestroy_MPIAIJ_PtAP;
2328:   ap->merge           = merge;

2330:   C->ops->mattransposemultnumeric = MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ;

2332:   if (PetscDefined(USE_INFO)) {
2333:     if (bi[pn] != 0) {
2334:       PetscCall(PetscInfo(C, "Reallocs %" PetscInt_FMT "; Fill ratio: given %g needed %g.\n", nspacedouble, (double)fill, (double)afill));
2335:       PetscCall(PetscInfo(C, "Use MatTransposeMatMult(A,B,MatReuse,%g,&C) for best performance.\n", (double)afill));
2336:     } else PetscCall(PetscInfo(C, "Empty matrix product\n"));
2337:   }
2338:   PetscFunctionReturn(PETSC_SUCCESS);
2339: }

2341: static PetscErrorCode MatProductSymbolic_AtB_MPIAIJ_MPIAIJ(Mat C)
2342: {
2343:   Mat_Product *product = C->product;
2344:   Mat          A = product->A, B = product->B;
2345:   PetscReal    fill = product->fill;
2346:   PetscBool    flg;

2348:   PetscFunctionBegin;
2349:   /* scalable */
2350:   PetscCall(PetscStrcmp(product->alg, "scalable", &flg));
2351:   if (flg || C->structure_only) {
2352:     if (C->structure_only) PetscCall(MatProductSetAlgorithm(C, "scalable"));
2353:     PetscCall(MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ(A, B, fill, C));
2354:     goto next;
2355:   }

2357:   /* nonscalable */
2358:   PetscCall(PetscStrcmp(product->alg, "nonscalable", &flg));
2359:   if (flg) {
2360:     PetscCall(MatTransposeMatMultSymbolic_MPIAIJ_MPIAIJ_nonscalable(A, B, fill, C));
2361:     goto next;
2362:   }

2364:   /* matmatmult */
2365:   PetscCall(PetscStrcmp(product->alg, "at*b", &flg));
2366:   if (flg) {
2367:     Mat                  At;
2368:     MatProductCtx_APMPI *ptap;

2370:     PetscCall(MatTranspose(A, MAT_INITIAL_MATRIX, &At));
2371:     PetscCall(MatMatMultSymbolic_MPIAIJ_MPIAIJ(At, B, fill, C));
2372:     ptap = (MatProductCtx_APMPI *)C->product->data;
2373:     if (ptap) {
2374:       ptap->Pt            = At;
2375:       C->product->destroy = MatProductCtxDestroy_MPIAIJ_PtAP;
2376:     }
2377:     C->ops->transposematmultnumeric = MatTransposeMatMultNumeric_MPIAIJ_MPIAIJ_matmatmult;
2378:     goto next;
2379:   }

2381:   /* backend general code */
2382:   PetscCall(PetscStrcmp(product->alg, "backend", &flg));
2383:   if (flg) {
2384:     PetscCall(MatProductSymbolic_MPIAIJBACKEND(C));
2385:     PetscFunctionReturn(PETSC_SUCCESS);
2386:   }

2388:   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "MatProduct type is not supported");

2390: next:
2391:   C->ops->productnumeric = MatProductNumeric_AtB;
2392:   PetscFunctionReturn(PETSC_SUCCESS);
2393: }

2395: /* Set options for MatMatMultxxx_MPIAIJ_MPIAIJ */
2396: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_AB(Mat C)
2397: {
2398:   Mat_Product *product = C->product;
2399:   Mat          A = product->A, B = product->B;
2400: #if PetscDefined(HAVE_HYPRE)
2401:   const char *algTypes[5] = {"scalable", "nonscalable", "seqmpi", "backend", "hypre"};
2402:   PetscInt    nalg        = 5;
2403: #else
2404:   const char *algTypes[4] = {
2405:     "scalable",
2406:     "nonscalable",
2407:     "seqmpi",
2408:     "backend",
2409:   };
2410:   PetscInt nalg = 4;
2411: #endif
2412:   PetscInt  alg = 1; /* set nonscalable algorithm as default */
2413:   PetscBool flg;
2414:   MPI_Comm  comm;

2416:   PetscFunctionBegin;
2417:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));

2419:   /* Set "nonscalable" as default algorithm */
2420:   PetscCall(PetscStrcmp(C->product->alg, "default", &flg));
2421:   if (flg) {
2422:     PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2424:     /* Set "scalable" as default if BN and local nonzeros of A and B are large */
2425:     if (B->cmap->N > 100000) { /* may switch to scalable algorithm as default */
2426:       MatInfo   Ainfo, Binfo;
2427:       PetscInt  nz_local;
2428:       PetscBool alg_scalable = PETSC_FALSE;

2430:       PetscCall(MatGetInfo(A, MAT_LOCAL, &Ainfo));
2431:       PetscCall(MatGetInfo(B, MAT_LOCAL, &Binfo));
2432:       nz_local = (PetscInt)(Ainfo.nz_allocated + Binfo.nz_allocated);

2434:       if (B->cmap->N > product->fill * nz_local) alg_scalable = PETSC_TRUE;
2435:       PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &alg_scalable, 1, MPI_C_BOOL, MPI_LOR, comm));

2437:       if (alg_scalable) {
2438:         alg = 0; /* scalable algorithm would 50% slower than nonscalable algorithm */
2439:         PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));
2440:         PetscCall(PetscInfo(B, "Use scalable algorithm, BN %" PetscInt_FMT ", fill*nz_allocated %g\n", B->cmap->N, (double)(product->fill * nz_local)));
2441:       }
2442:     }
2443:   }

2445:   /* Get runtime option */
2446:   if (product->api_user) {
2447:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatMatMult", "Mat");
2448:     PetscCall(PetscOptionsEList("-matmatmult_via", "Algorithmic approach", "MatMatMult", algTypes, nalg, algTypes[alg], &alg, &flg));
2449:     PetscOptionsEnd();
2450:   } else {
2451:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_AB", "Mat");
2452:     PetscCall(PetscOptionsEList("-mat_product_algorithm", "Algorithmic approach", "MatMatMult", algTypes, nalg, algTypes[alg], &alg, &flg));
2453:     PetscOptionsEnd();
2454:   }
2455:   if (flg) PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2457:   C->ops->productsymbolic = MatProductSymbolic_AB_MPIAIJ_MPIAIJ;
2458:   PetscFunctionReturn(PETSC_SUCCESS);
2459: }

2461: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_ABt(Mat C)
2462: {
2463:   PetscFunctionBegin;
2464:   PetscCall(MatProductSetFromOptions_MPIAIJ_AB(C));
2465:   C->ops->productsymbolic = MatProductSymbolic_ABt_MPIAIJ_MPIAIJ;
2466:   PetscFunctionReturn(PETSC_SUCCESS);
2467: }

2469: /* Set options for MatTransposeMatMultXXX_MPIAIJ_MPIAIJ */
2470: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_AtB(Mat C)
2471: {
2472:   Mat_Product *product = C->product;
2473:   Mat          A = product->A, B = product->B;
2474:   const char  *algTypes[4] = {"scalable", "nonscalable", "at*b", "backend"};
2475:   PetscInt     nalg        = 4;
2476:   PetscInt     alg         = 1; /* set default algorithm  */
2477:   PetscBool    flg;
2478:   MPI_Comm     comm;

2480:   PetscFunctionBegin;
2481:   /* Check matrix local sizes */
2482:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
2483:   PetscCheck(A->rmap->rstart == B->rmap->rstart && A->rmap->rend == B->rmap->rend, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Matrix local dimensions are incompatible, A (%" PetscInt_FMT ", %" PetscInt_FMT ") != B (%" PetscInt_FMT ",%" PetscInt_FMT ")",
2484:              A->rmap->rstart, A->rmap->rend, B->rmap->rstart, B->rmap->rend);

2486:   /* Set default algorithm */
2487:   PetscCall(PetscStrcmp(C->product->alg, "default", &flg));
2488:   if (flg) PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2490:   /* Set "scalable" as default if BN and local nonzeros of A and B are large */
2491:   if (alg && B->cmap->N > 100000) { /* may switch to scalable algorithm as default */
2492:     MatInfo   Ainfo, Binfo;
2493:     PetscInt  nz_local;
2494:     PetscBool alg_scalable = PETSC_FALSE;

2496:     PetscCall(MatGetInfo(A, MAT_LOCAL, &Ainfo));
2497:     PetscCall(MatGetInfo(B, MAT_LOCAL, &Binfo));
2498:     nz_local = (PetscInt)(Ainfo.nz_allocated + Binfo.nz_allocated);

2500:     if (B->cmap->N > product->fill * nz_local) alg_scalable = PETSC_TRUE;
2501:     PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &alg_scalable, 1, MPI_C_BOOL, MPI_LOR, comm));

2503:     if (alg_scalable) {
2504:       alg = 0; /* scalable algorithm would 50% slower than nonscalable algorithm */
2505:       PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));
2506:       PetscCall(PetscInfo(B, "Use scalable algorithm, BN %" PetscInt_FMT ", fill*nz_allocated %g\n", B->cmap->N, (double)(product->fill * nz_local)));
2507:     }
2508:   }

2510:   /* Get runtime option */
2511:   if (product->api_user) {
2512:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatTransposeMatMult", "Mat");
2513:     PetscCall(PetscOptionsEList("-mattransposematmult_via", "Algorithmic approach", "MatTransposeMatMult", algTypes, nalg, algTypes[alg], &alg, &flg));
2514:     PetscOptionsEnd();
2515:   } else {
2516:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_AtB", "Mat");
2517:     PetscCall(PetscOptionsEList("-mat_product_algorithm", "Algorithmic approach", "MatTransposeMatMult", algTypes, nalg, algTypes[alg], &alg, &flg));
2518:     PetscOptionsEnd();
2519:   }
2520:   if (flg) PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2522:   C->ops->productsymbolic = MatProductSymbolic_AtB_MPIAIJ_MPIAIJ;
2523:   PetscFunctionReturn(PETSC_SUCCESS);
2524: }

2526: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_PtAP(Mat C)
2527: {
2528:   Mat_Product *product = C->product;
2529:   Mat          A = product->A, P = product->B;
2530:   MPI_Comm     comm;
2531:   PetscBool    flg;
2532:   PetscInt     alg = 1; /* set default algorithm */
2533: #if !PetscDefined(HAVE_HYPRE)
2534:   const char *algTypes[5] = {"scalable", "nonscalable", "allatonce", "allatonce_merged", "backend"};
2535:   PetscInt    nalg        = 5;
2536: #else
2537:   const char *algTypes[6] = {"scalable", "nonscalable", "allatonce", "allatonce_merged", "backend", "hypre"};
2538:   PetscInt    nalg        = 6;
2539: #endif
2540:   PetscInt pN = P->cmap->N;

2542:   PetscFunctionBegin;
2543:   /* Check matrix local sizes */
2544:   PetscCall(PetscObjectGetComm((PetscObject)C, &comm));
2545:   PetscCheck(A->rmap->rstart == P->rmap->rstart && A->rmap->rend == P->rmap->rend, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Matrix local dimensions are incompatible, Arow (%" PetscInt_FMT ", %" PetscInt_FMT ") != Prow (%" PetscInt_FMT ",%" PetscInt_FMT ")",
2546:              A->rmap->rstart, A->rmap->rend, P->rmap->rstart, P->rmap->rend);
2547:   PetscCheck(A->cmap->rstart == P->rmap->rstart && A->cmap->rend == P->rmap->rend, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Matrix local dimensions are incompatible, Acol (%" PetscInt_FMT ", %" PetscInt_FMT ") != Prow (%" PetscInt_FMT ",%" PetscInt_FMT ")",
2548:              A->cmap->rstart, A->cmap->rend, P->rmap->rstart, P->rmap->rend);

2550:   /* Set "nonscalable" as default algorithm */
2551:   PetscCall(PetscStrcmp(C->product->alg, "default", &flg));
2552:   if (flg) {
2553:     PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2555:     /* Set "scalable" as default if BN and local nonzeros of A and B are large */
2556:     if (pN > 100000) {
2557:       MatInfo   Ainfo, Pinfo;
2558:       PetscInt  nz_local;
2559:       PetscBool alg_scalable = PETSC_FALSE;

2561:       PetscCall(MatGetInfo(A, MAT_LOCAL, &Ainfo));
2562:       PetscCall(MatGetInfo(P, MAT_LOCAL, &Pinfo));
2563:       nz_local = (PetscInt)(Ainfo.nz_allocated + Pinfo.nz_allocated);

2565:       if (pN > product->fill * nz_local) alg_scalable = PETSC_TRUE;
2566:       PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, &alg_scalable, 1, MPI_C_BOOL, MPI_LOR, comm));

2568:       if (alg_scalable) {
2569:         alg = 0; /* scalable algorithm would 50% slower than nonscalable algorithm */
2570:         PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));
2571:       }
2572:     }
2573:   }

2575:   /* Get runtime option */
2576:   if (product->api_user) {
2577:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatPtAP", "Mat");
2578:     PetscCall(PetscOptionsEList("-matptap_via", "Algorithmic approach", "MatPtAP", algTypes, nalg, algTypes[alg], &alg, &flg));
2579:     PetscOptionsEnd();
2580:   } else {
2581:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_PtAP", "Mat");
2582:     PetscCall(PetscOptionsEList("-mat_product_algorithm", "Algorithmic approach", "MatPtAP", algTypes, nalg, algTypes[alg], &alg, &flg));
2583:     PetscOptionsEnd();
2584:   }
2585:   if (flg) PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2587:   C->ops->productsymbolic = MatProductSymbolic_PtAP_MPIAIJ_MPIAIJ;
2588:   PetscFunctionReturn(PETSC_SUCCESS);
2589: }

2591: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_RARt(Mat C)
2592: {
2593:   Mat_Product *product = C->product;
2594:   Mat          A = product->A, R = product->B;

2596:   PetscFunctionBegin;
2597:   /* Check matrix local sizes */
2598:   PetscCheck(A->cmap->n == R->cmap->n && A->rmap->n == R->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Matrix local dimensions are incompatible, A local (%" PetscInt_FMT ", %" PetscInt_FMT "), R local (%" PetscInt_FMT ",%" PetscInt_FMT ")", A->rmap->n,
2599:              A->rmap->n, R->rmap->n, R->cmap->n);

2601:   C->ops->productsymbolic = MatProductSymbolic_RARt_MPIAIJ_MPIAIJ;
2602:   PetscFunctionReturn(PETSC_SUCCESS);
2603: }

2605: /*
2606:  Set options for ABC = A*B*C = A*(B*C); ABC's algorithm must be chosen from AB's algorithm
2607: */
2608: static PetscErrorCode MatProductSetFromOptions_MPIAIJ_ABC(Mat C)
2609: {
2610:   Mat_Product *product     = C->product;
2611:   PetscBool    flg         = PETSC_FALSE;
2612:   PetscInt     alg         = 1; /* default algorithm */
2613:   const char  *algTypes[3] = {"scalable", "nonscalable", "seqmpi"};
2614:   PetscInt     nalg        = 3;

2616:   PetscFunctionBegin;
2617:   /* Set default algorithm */
2618:   PetscCall(PetscStrcmp(C->product->alg, "default", &flg));
2619:   if (flg) PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2621:   /* Get runtime option */
2622:   if (product->api_user) {
2623:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatMatMatMult", "Mat");
2624:     PetscCall(PetscOptionsEList("-matmatmatmult_via", "Algorithmic approach", "MatMatMatMult", algTypes, nalg, algTypes[alg], &alg, &flg));
2625:     PetscOptionsEnd();
2626:   } else {
2627:     PetscOptionsBegin(PetscObjectComm((PetscObject)C), ((PetscObject)C)->prefix, "MatProduct_ABC", "Mat");
2628:     PetscCall(PetscOptionsEList("-mat_product_algorithm", "Algorithmic approach", "MatProduct_ABC", algTypes, nalg, algTypes[alg], &alg, &flg));
2629:     PetscOptionsEnd();
2630:   }
2631:   if (flg) PetscCall(MatProductSetAlgorithm(C, algTypes[alg]));

2633:   C->ops->matmatmultsymbolic = MatMatMatMultSymbolic_MPIAIJ_MPIAIJ_MPIAIJ;
2634:   C->ops->productsymbolic    = MatProductSymbolic_ABC;
2635:   PetscFunctionReturn(PETSC_SUCCESS);
2636: }

2638: PETSC_INTERN PetscErrorCode MatProductSetFromOptions_MPIAIJ(Mat C)
2639: {
2640:   Mat_Product *product = C->product;

2642:   PetscFunctionBegin;
2643:   switch (product->type) {
2644:   case MATPRODUCT_AB:
2645:     PetscCall(MatProductSetFromOptions_MPIAIJ_AB(C));
2646:     break;
2647:   case MATPRODUCT_ABt:
2648:     PetscCall(MatProductSetFromOptions_MPIAIJ_ABt(C));
2649:     break;
2650:   case MATPRODUCT_AtB:
2651:     PetscCall(MatProductSetFromOptions_MPIAIJ_AtB(C));
2652:     break;
2653:   case MATPRODUCT_PtAP:
2654:     PetscCall(MatProductSetFromOptions_MPIAIJ_PtAP(C));
2655:     break;
2656:   case MATPRODUCT_RARt:
2657:     PetscCall(MatProductSetFromOptions_MPIAIJ_RARt(C));
2658:     break;
2659:   case MATPRODUCT_ABC:
2660:     PetscCall(MatProductSetFromOptions_MPIAIJ_ABC(C));
2661:     break;
2662:   default:
2663:     break;
2664:   }
2665:   PetscFunctionReturn(PETSC_SUCCESS);
2666: }