Actual source code: aijhipsparse.hip.cxx

  1: /*
  2:   Defines the basic matrix operations for the AIJ (compressed row)
  3:   matrix storage format using the HIPSPARSE library,
  4:   Portions of this code are under:
  5:   Copyright (c) 2022 Advanced Micro Devices, Inc. All rights reserved.
  6: */
  7: #include <../src/mat/impls/aij/seq/aij.h>
  8: #include <petscpkg_version.h>
  9: #include <../src/mat/impls/sbaij/seq/sbaij.h>
 10: #include <../src/mat/impls/dense/seq/dense.h>
 11: #include <../src/vec/vec/impls/dvecimpl.h>
 12: #include <petsc/private/vecimpl.h>
 13: #undef VecType
 14: #include <../src/mat/impls/aij/seq/seqhipsparse/hipsparsematimpl.h>
 15: #include <../src/mat/impls/aij/seq/cupm/aijcupm.hpp>
 16: #include <thrust/adjacent_difference.h>
 17: #include <thrust/iterator/transform_iterator.h>
 18: #include <thrust/iterator/constant_iterator.h>
 19: #include <thrust/iterator/discard_iterator.h>
 20: #include <thrust/binary_search.h>
 21: #include <thrust/remove.h>
 22: #include <thrust/sort.h>
 23: #include <thrust/unique.h>
 24: #include <thrust/gather.h>
 25: #include <thrust/functional.h>

 27: const char *const MatHIPSPARSEStorageFormats[] = {"CSR", "ELL", "HYB", "MatHIPSPARSEStorageFormat", "MAT_HIPSPARSE_", 0};
 28: const char *const MatHIPSPARSESpMVAlgorithms[] = {"MV_ALG_DEFAULT", "COOMV_ALG", "CSRMV_ALG1", "CSRMV_ALG2", "SPMV_ALG_DEFAULT", "SPMV_COO_ALG1", "SPMV_COO_ALG2", "SPMV_CSR_ALG1", "SPMV_CSR_ALG2", "hipsparseSpMVAlg_t", "HIPSPARSE_", 0};
 29: const char *const MatHIPSPARSESpMMAlgorithms[] = {"ALG_DEFAULT", "COO_ALG1", "COO_ALG2", "COO_ALG3", "CSR_ALG1", "COO_ALG4", "CSR_ALG2", "hipsparseSpMMAlg_t", "HIPSPARSE_SPMM_", 0};
 30: //const char *const MatHIPSPARSECsr2CscAlgorithms[] = {"INVALID"/*HIPSPARSE does not have enum 0! We created one*/, "ALG1", "ALG2", "hipsparseCsr2CscAlg_t", "HIPSPARSE_CSR2CSC_", 0};

 32: static PetscErrorCode MatICCFactorSymbolic_SeqAIJHIPSPARSE(Mat, Mat, IS, const MatFactorInfo *);
 33: static PetscErrorCode MatCholeskyFactorSymbolic_SeqAIJHIPSPARSE(Mat, Mat, IS, const MatFactorInfo *);
 34: static PetscErrorCode MatCholeskyFactorNumeric_SeqAIJHIPSPARSE(Mat, Mat, const MatFactorInfo *);
 35: static PetscErrorCode MatILUFactorSymbolic_SeqAIJHIPSPARSE(Mat, Mat, IS, IS, const MatFactorInfo *);
 36: static PetscErrorCode MatSetFromOptions_SeqAIJHIPSPARSE(Mat, PetscOptionItems PetscOptionsObject);
 37: static PetscErrorCode MatAXPY_SeqAIJHIPSPARSE(Mat, PetscScalar, Mat, MatStructure);
 38: static PetscErrorCode MatScale_SeqAIJHIPSPARSE(Mat, PetscScalar);
 39: static PetscErrorCode MatDiagonalScale_SeqAIJHIPSPARSE(Mat, Vec, Vec);
 40: static PetscErrorCode MatMult_SeqAIJHIPSPARSE(Mat, Vec, Vec);
 41: static PetscErrorCode MatMultAdd_SeqAIJHIPSPARSE(Mat, Vec, Vec, Vec);
 42: static PetscErrorCode MatMultTranspose_SeqAIJHIPSPARSE(Mat, Vec, Vec);
 43: static PetscErrorCode MatMultTransposeAdd_SeqAIJHIPSPARSE(Mat, Vec, Vec, Vec);
 44: static PetscErrorCode MatMultHermitianTranspose_SeqAIJHIPSPARSE(Mat, Vec, Vec);
 45: static PetscErrorCode MatMultHermitianTransposeAdd_SeqAIJHIPSPARSE(Mat, Vec, Vec, Vec);
 46: static PetscErrorCode MatMultAddKernel_SeqAIJHIPSPARSE(Mat, Vec, Vec, Vec, PetscBool, PetscBool);

 48: static PetscErrorCode CsrMatrix_Destroy(CsrMatrix **);
 49: static PetscErrorCode MatSeqAIJHIPSPARSEMultStruct_Destroy(Mat_SeqAIJHIPSPARSEMultStruct **, MatHIPSPARSEStorageFormat);
 50: static PetscErrorCode MatSeqAIJHIPSPARSETriFactors_Destroy(Mat_SeqAIJHIPSPARSETriFactors **);
 51: static PetscErrorCode MatSeqAIJHIPSPARSE_Destroy(Mat);

 53: static PetscErrorCode MatSeqAIJHIPSPARSECopyFromGPU(Mat);
 54: static PetscErrorCode MatSeqAIJHIPSPARSEInvalidateTranspose(Mat, PetscBool);

 56: static PetscErrorCode MatSeqAIJCopySubArray_SeqAIJHIPSPARSE(Mat, PetscInt, const PetscInt[], PetscScalar[]);
 57: static PetscErrorCode MatSetPreallocationCOO_SeqAIJHIPSPARSE(Mat, PetscCount, PetscInt[], PetscInt[]);
 58: static PetscErrorCode MatSetValuesCOO_SeqAIJHIPSPARSE(Mat, const PetscScalar[], InsertMode);

 60: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJHIPSPARSE(Mat, MatType, MatReuse, Mat *);

 62: // cusparseCreateCsr() separates types for row offsets and column indices in prototype, but requires them to have the same type at runtime!
 63: const hipsparseIndexType_t csrRowOffsetsType = PetscDefined(USE_64BIT_INDICES) ? HIPSPARSE_INDEX_64I : HIPSPARSE_INDEX_32I;
 64: const hipsparseIndexType_t csrColIndType     = PetscDefined(USE_64BIT_INDICES) ? HIPSPARSE_INDEX_64I : HIPSPARSE_INDEX_32I;

 66: /* Policy struct for MatSeqAIJCUSPARSE_CUPM shared template (HIP specialisation) */
 67: struct MatSeqAIJHIPSPARSE_Policy {
 68:   typedef Mat_SeqAIJHIPSPARSE           mat_struct_type;
 69:   typedef Mat_SeqAIJHIPSPARSEMultStruct mult_struct_type;

 71:   static int storage_format_csr() { return (int)MAT_HIPSPARSE_CSR; }
 72:   static int storage_format_ell() { return (int)MAT_HIPSPARSE_ELL; }
 73:   static int storage_format_hyb() { return (int)MAT_HIPSPARSE_HYB; }

 75:   static PetscErrorCode CopyToGPU(Mat A) { return MatSeqAIJHIPSPARSECopyToGPU(A); }
 76:   static PetscErrorCode CopyFromGPU(Mat A) { return MatSeqAIJHIPSPARSECopyFromGPU(A); }
 77:   static PetscErrorCode InvalidateTranspose(Mat A, PetscBool d) { return MatSeqAIJHIPSPARSEInvalidateTranspose(A, d); }
 78:   static PetscErrorCode ConvertFromSeqAIJ(Mat B, MatType t, MatReuse r, Mat *C) { return MatConvert_SeqAIJ_SeqAIJHIPSPARSE(B, t, r, C); }
 79:   static const char    *mat_type_name;

 81:   static PetscErrorCode Destroy(Mat A) { return MatSeqAIJHIPSPARSE_Destroy(A); }
 82:   static PetscErrorCode TriFactorsDestroy(void **spptr) { return MatSeqAIJHIPSPARSETriFactors_Destroy((Mat_SeqAIJHIPSPARSETriFactors **)spptr); }
 83:   static const char    *set_format_c;
 84:   static const char    *set_use_cpu_solve_c;
 85:   static const char    *product_seqdense_device_c;
 86:   static const char    *product_seqdense_c;
 87:   static const char    *product_self_c;
 88:   static const char    *seq_convert_hypre_c;

 90:   static PetscErrorCode VecGetArrayRead(Vec v, const PetscScalar **a) { return VecHIPGetArrayRead(v, a); }
 91:   static PetscErrorCode VecRestoreArrayRead(Vec v, const PetscScalar **a) { return VecHIPRestoreArrayRead(v, a); }
 92:   static PetscErrorCode VecGetArrayWrite(Vec v, PetscScalar **a) { return VecHIPGetArrayWrite(v, a); }
 93:   static PetscErrorCode VecRestoreArrayWrite(Vec v, PetscScalar **a) { return VecHIPRestoreArrayWrite(v, a); }
 94: };
 95: const char *MatSeqAIJHIPSPARSE_Policy::mat_type_name             = MATSEQAIJHIPSPARSE;
 96: const char *MatSeqAIJHIPSPARSE_Policy::set_format_c              = "MatHIPSPARSESetFormat_C";
 97: const char *MatSeqAIJHIPSPARSE_Policy::set_use_cpu_solve_c       = "MatHIPSPARSESetUseCPUSolve_C";
 98: const char *MatSeqAIJHIPSPARSE_Policy::product_seqdense_device_c = "MatProductSetFromOptions_seqaijhipsparse_seqdensehip_C";
 99: const char *MatSeqAIJHIPSPARSE_Policy::product_seqdense_c        = "MatProductSetFromOptions_seqaijhipsparse_seqdense_C";
100: const char *MatSeqAIJHIPSPARSE_Policy::product_self_c            = "MatProductSetFromOptions_seqaijhipsparse_seqaijhipsparse_C";
101: const char *MatSeqAIJHIPSPARSE_Policy::seq_convert_hypre_c       = "MatConvert_seqaijhipsparse_hypre_C";

103: using MatSeqAIJHIPSPARSE_CUPM_t = Petsc::mat::aij::cupm::impl::MatSeqAIJCUSPARSE_CUPM<Petsc::device::cupm::DeviceType::HIP, MatSeqAIJHIPSPARSE_Policy>;

105: using SparsePointerModeGuard = Petsc::device::cupm::impl::CUPMSparsePointerModeGuard<Petsc::device::cupm::DeviceType::HIP>;

107: using Csr2coo        = Petsc::mat::aij::cupm::impl::Csr2coo;
108: using PetscIntToCInt = Petsc::mat::aij::cupm::impl::PetscIntToCInt;

110: PETSC_INTERN PetscErrorCode MatHIPSPARSESetFormat_SeqAIJHIPSPARSE(Mat A, MatHIPSPARSEFormatOperation op, MatHIPSPARSEStorageFormat format)
111: {
112:   Mat_SeqAIJHIPSPARSE *hipsparsestruct = (Mat_SeqAIJHIPSPARSE *)A->spptr;

114:   PetscFunctionBegin;
115:   switch (op) {
116:   case MAT_HIPSPARSE_MULT:
117:     hipsparsestruct->format = format;
118:     break;
119:   case MAT_HIPSPARSE_ALL:
120:     hipsparsestruct->format = format;
121:     break;
122:   default:
123:     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "unsupported operation %d for MatHIPSPARSEFormatOperation. MAT_HIPSPARSE_MULT and MAT_HIPSPARSE_ALL are currently supported.", op);
124:   }
125:   PetscFunctionReturn(PETSC_SUCCESS);
126: }

128: /*@
129:   MatHIPSPARSESetFormat - Sets the storage format of `MATSEQHIPSPARSE` matrices for a particular
130:   operation. Only the `MatMult()` operation can use different GPU storage formats

132:   Not Collective

134:   Input Parameters:
135: + A      - Matrix of type `MATSEQAIJHIPSPARSE`
136: . op     - `MatHIPSPARSEFormatOperation`. `MATSEQAIJHIPSPARSE` matrices support `MAT_HIPSPARSE_MULT` and `MAT_HIPSPARSE_ALL`.
137:          `MATMPIAIJHIPSPARSE` matrices support `MAT_HIPSPARSE_MULT_DIAG`, `MAT_HIPSPARSE_MULT_OFFDIAG`, and `MAT_HIPSPARSE_ALL`.
138: - format - `MatHIPSPARSEStorageFormat` (one of `MAT_HIPSPARSE_CSR`, `MAT_HIPSPARSE_ELL`, `MAT_HIPSPARSE_HYB`.)

140:   Level: intermediate

142: .seealso: [](ch_matrices), `Mat`, `MATSEQAIJHIPSPARSE`, `MatHIPSPARSEStorageFormat`, `MatHIPSPARSEFormatOperation`
143: @*/
144: PetscErrorCode MatHIPSPARSESetFormat(Mat A, MatHIPSPARSEFormatOperation op, MatHIPSPARSEStorageFormat format)
145: {
146:   PetscFunctionBegin;
148:   PetscTryMethod(A, "MatHIPSPARSESetFormat_C", (Mat, MatHIPSPARSEFormatOperation, MatHIPSPARSEStorageFormat), (A, op, format));
149:   PetscFunctionReturn(PETSC_SUCCESS);
150: }

152: PETSC_INTERN PetscErrorCode MatHIPSPARSESetUseCPUSolve_SeqAIJHIPSPARSE(Mat A, PetscBool use_cpu)
153: {
154:   Mat_SeqAIJHIPSPARSE *hipsparsestruct = (Mat_SeqAIJHIPSPARSE *)A->spptr;

156:   PetscFunctionBegin;
157:   hipsparsestruct->use_cpu_solve = use_cpu;
158:   PetscFunctionReturn(PETSC_SUCCESS);
159: }

161: /*@
162:   MatHIPSPARSESetUseCPUSolve - Sets use CPU `MatSolve()`.

164:   Input Parameters:
165: + A       - Matrix of type `MATSEQAIJHIPSPARSE`
166: - use_cpu - set flag for using the built-in CPU `MatSolve()`

168:   Level: intermediate

170:   Notes:
171:   The hipSparse LU solver currently computes the factors with the built-in CPU method
172:   and moves the factors to the GPU for the solve. We have observed better performance keeping the data on the CPU and computing the solve there.
173:   This method to specifies if the solve is done on the CPU or GPU (GPU is the default).

175: .seealso: [](ch_matrices), `Mat`, `MatSolve()`, `MATSEQAIJHIPSPARSE`, `MatHIPSPARSEStorageFormat`, `MatHIPSPARSEFormatOperation`
176: @*/
177: PetscErrorCode MatHIPSPARSESetUseCPUSolve(Mat A, PetscBool use_cpu)
178: {
179:   PetscFunctionBegin;
181:   PetscTryMethod(A, "MatHIPSPARSESetUseCPUSolve_C", (Mat, PetscBool), (A, use_cpu));
182:   PetscFunctionReturn(PETSC_SUCCESS);
183: }

185: static PetscErrorCode MatSetOption_SeqAIJHIPSPARSE(Mat A, MatOption op, PetscBool flg)
186: {
187:   PetscFunctionBegin;
188:   switch (op) {
189:   case MAT_FORM_EXPLICIT_TRANSPOSE:
190:     /* need to destroy the transpose matrix if present to prevent from logic errors if flg is set to true later */
191:     if (A->form_explicit_transpose && !flg) PetscCall(MatSeqAIJHIPSPARSEInvalidateTranspose(A, PETSC_TRUE));
192:     A->form_explicit_transpose = flg;
193:     break;
194:   default:
195:     PetscCall(MatSetOption_SeqAIJ(A, op, flg));
196:     break;
197:   }
198:   PetscFunctionReturn(PETSC_SUCCESS);
199: }

201: static PetscErrorCode MatSetFromOptions_SeqAIJHIPSPARSE(Mat A, PetscOptionItems PetscOptionsObject)
202: {
203:   MatHIPSPARSEStorageFormat format;
204:   PetscBool                 flg;
205:   Mat_SeqAIJHIPSPARSE      *hipsparsestruct = (Mat_SeqAIJHIPSPARSE *)A->spptr;

207:   PetscFunctionBegin;
208:   PetscOptionsHeadBegin(PetscOptionsObject, "SeqAIJHIPSPARSE options");
209:   if (A->factortype == MAT_FACTOR_NONE) {
210:     PetscCall(PetscOptionsEnum("-mat_hipsparse_mult_storage_format", "sets storage format of (seq)aijhipsparse gpu matrices for SpMV", "MatHIPSPARSESetFormat", MatHIPSPARSEStorageFormats, (PetscEnum)hipsparsestruct->format, (PetscEnum *)&format, &flg));
211:     if (flg) PetscCall(MatHIPSPARSESetFormat(A, MAT_HIPSPARSE_MULT, format));
212:     PetscCall(PetscOptionsEnum("-mat_hipsparse_storage_format", "sets storage format of (seq)aijhipsparse gpu matrices for SpMV and TriSolve", "MatHIPSPARSESetFormat", MatHIPSPARSEStorageFormats, (PetscEnum)hipsparsestruct->format, (PetscEnum *)&format, &flg));
213:     if (flg) PetscCall(MatHIPSPARSESetFormat(A, MAT_HIPSPARSE_ALL, format));
214:     PetscCall(PetscOptionsBool("-mat_hipsparse_use_cpu_solve", "Use CPU (I)LU solve", "MatHIPSPARSESetUseCPUSolve", hipsparsestruct->use_cpu_solve, &hipsparsestruct->use_cpu_solve, &flg));
215:     if (flg) PetscCall(MatHIPSPARSESetUseCPUSolve(A, hipsparsestruct->use_cpu_solve));
216:     PetscCall(
217:       PetscOptionsEnum("-mat_hipsparse_spmv_alg", "sets hipSPARSE algorithm used in sparse-mat dense-vector multiplication (SpMV)", "hipsparseSpMVAlg_t", MatHIPSPARSESpMVAlgorithms, (PetscEnum)hipsparsestruct->spmvAlg, (PetscEnum *)&hipsparsestruct->spmvAlg, &flg));
218:     /* If user did use this option, check its consistency with hipSPARSE, since PetscOptionsEnum() sets enum values based on their position in MatHIPSPARSESpMVAlgorithms[] */
219:     PetscCheck(!flg || HIPSPARSE_SPMV_CSR_ALG1 == 2, PETSC_COMM_SELF, PETSC_ERR_SUP, "hipSPARSE enum hipsparseSpMVAlg_t has been changed but PETSc has not been updated accordingly");
220:     PetscCall(
221:       PetscOptionsEnum("-mat_hipsparse_spmm_alg", "sets hipSPARSE algorithm used in sparse-mat dense-mat multiplication (SpMM)", "hipsparseSpMMAlg_t", MatHIPSPARSESpMMAlgorithms, (PetscEnum)hipsparsestruct->spmmAlg, (PetscEnum *)&hipsparsestruct->spmmAlg, &flg));
222:     PetscCheck(!flg || HIPSPARSE_SPMM_CSR_ALG1 == 4, PETSC_COMM_SELF, PETSC_ERR_SUP, "hipSPARSE enum hipsparseSpMMAlg_t has been changed but PETSc has not been updated accordingly");
223:     /*
224:     PetscCall(PetscOptionsEnum("-mat_hipsparse_csr2csc_alg", "sets hipSPARSE algorithm used in converting CSR matrices to CSC matrices", "hipsparseCsr2CscAlg_t", MatHIPSPARSECsr2CscAlgorithms, (PetscEnum)hipsparsestruct->csr2cscAlg, (PetscEnum*)&hipsparsestruct->csr2cscAlg, &flg));
225:     PetscCheck(!flg || HIPSPARSE_CSR2CSC_ALG1 == 1, PETSC_COMM_SELF, PETSC_ERR_SUP, "hipSPARSE enum hipsparseCsr2CscAlg_t has been changed but PETSc has not been updated accordingly");
226:     */
227:   }
228:   PetscOptionsHeadEnd();
229:   PetscFunctionReturn(PETSC_SUCCESS);
230: }

232: static PetscErrorCode MatSeqAIJHIPSPARSEBuildFactoredMatrix_LU(Mat A)
233: {
234:   Mat_SeqAIJ                    *a  = static_cast<Mat_SeqAIJ *>(A->data);
235:   PetscInt                       m  = A->rmap->n;
236:   Mat_SeqAIJHIPSPARSETriFactors *fs = static_cast<Mat_SeqAIJHIPSPARSETriFactors *>(A->spptr);
237:   const PetscInt                *Ai = a->i, *Aj = a->j, *adiag;
238:   const MatScalar               *Aa = a->a;
239:   PetscInt                      *Mi, *Mj, Mnz;
240:   PetscScalar                   *Ma;
241:   PetscDeviceContext             dctx;
242:   hipStream_t                    stream;
243:   hipsparseHandle_t              handle;

245:   PetscFunctionBegin;
246:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetSparseHandles_(&dctx, &handle, &stream));
247:   {
248:     const SparsePointerModeGuard pointer_mode{handle, HIPSPARSE_POINTER_MODE_HOST};

250:     PetscCall(MatGetDiagonalMarkers_SeqAIJ(A, &adiag, NULL));
251:     if (A->offloadmask == PETSC_OFFLOAD_CPU) { // A's latest factors are on CPU
252:       if (!fs->csrRowPtr) {                    // Is this the first time we are doing setup? Use csrRowPtr since it is not null even when m=0
253:         // Re-arrange the (skewed) factored matrix and put the result into M, a regular csr matrix on host
254:         Mnz = (Ai[m] - Ai[0]) + (adiag[0] - adiag[m]); // Lnz (without the unit diagonal) + Unz (with the non-unit diagonal)
255:         PetscCall(PetscMalloc1(m + 1, &Mi));
256:         PetscCall(PetscMalloc1(Mnz, &Mj)); // Mj is temp
257:         PetscCall(PetscMalloc1(Mnz, &Ma));
258:         Mi[0] = 0;
259:         for (PetscInt i = 0; i < m; i++) {
260:           PetscInt llen = Ai[i + 1] - Ai[i];
261:           PetscInt ulen = adiag[i] - adiag[i + 1];
262:           PetscCall(PetscArraycpy(Mj + Mi[i], Aj + Ai[i], llen));                           // entries of L
263:           Mj[Mi[i] + llen] = i;                                                             // diagonal entry
264:           PetscCall(PetscArraycpy(Mj + Mi[i] + llen + 1, Aj + adiag[i + 1] + 1, ulen - 1)); // entries of U on the right of the diagonal
265:           Mi[i + 1] = Mi[i] + llen + ulen;
266:         }
267:         // Copy M (L,U) from host to device
268:         PetscCallHIP(hipMalloc(&fs->csrRowPtr, sizeof(*fs->csrRowPtr) * (m + 1)));
269:         PetscCallHIP(hipMalloc(&fs->csrColIdx, sizeof(*fs->csrColIdx) * Mnz));
270:         PetscCallHIP(hipMalloc(&fs->csrVal, sizeof(*fs->csrVal) * Mnz));
271:         PetscCallHIP(hipMemcpyAsync(fs->csrRowPtr, Mi, sizeof(*fs->csrRowPtr) * (m + 1), hipMemcpyHostToDevice, stream));
272:         PetscCallHIP(hipMemcpyAsync(fs->csrColIdx, Mj, sizeof(*fs->csrColIdx) * Mnz, hipMemcpyHostToDevice, stream));
273:         PetscCall(PetscDeviceContextSynchronize(dctx));

275:         // Create descriptors for L, U. See https://docs.nvidia.com/cuda/cusparse/index.html#cusparseDiagType_t
276:         // cusparseDiagType_t: This type indicates if the matrix diagonal entries are unity. The diagonal elements are always
277:         // assumed to be present, but if CUSPARSE_DIAG_TYPE_UNIT is passed to an API routine, then the routine assumes that
278:         // all diagonal entries are unity and will not read or modify those entries. Note that in this case the routine
279:         // assumes the diagonal entries are equal to one, regardless of what those entries are actually set to in memory.
280:         hipsparseFillMode_t fillMode = HIPSPARSE_FILL_MODE_LOWER;
281:         hipsparseDiagType_t diagType = HIPSPARSE_DIAG_TYPE_UNIT;

283:         PetscCallHIPSPARSE(hipsparseCreateCsr(&fs->spMatDescr_L, m, m, Mnz, fs->csrRowPtr, fs->csrColIdx, fs->csrVal, csrRowOffsetsType, csrColIndType, HIPSPARSE_INDEX_BASE_ZERO, hipsparse_scalartype));
284:         PetscCallHIPSPARSE(hipsparseSpMatSetAttribute(fs->spMatDescr_L, HIPSPARSE_SPMAT_FILL_MODE, &fillMode, sizeof(fillMode)));
285:         PetscCallHIPSPARSE(hipsparseSpMatSetAttribute(fs->spMatDescr_L, HIPSPARSE_SPMAT_DIAG_TYPE, &diagType, sizeof(diagType)));

287:         fillMode = HIPSPARSE_FILL_MODE_UPPER;
288:         diagType = HIPSPARSE_DIAG_TYPE_NON_UNIT;
289:         PetscCallHIPSPARSE(hipsparseCreateCsr(&fs->spMatDescr_U, m, m, Mnz, fs->csrRowPtr, fs->csrColIdx, fs->csrVal, csrRowOffsetsType, csrColIndType, HIPSPARSE_INDEX_BASE_ZERO, hipsparse_scalartype));
290:         PetscCallHIPSPARSE(hipsparseSpMatSetAttribute(fs->spMatDescr_U, HIPSPARSE_SPMAT_FILL_MODE, &fillMode, sizeof(fillMode)));
291:         PetscCallHIPSPARSE(hipsparseSpMatSetAttribute(fs->spMatDescr_U, HIPSPARSE_SPMAT_DIAG_TYPE, &diagType, sizeof(diagType)));

293:         // Allocate work vectors in SpSv
294:         PetscCallHIP(hipMalloc((void **)&fs->X, sizeof(*fs->X) * m));
295:         PetscCallHIP(hipMalloc((void **)&fs->Y, sizeof(*fs->Y) * m));

297:         PetscCallHIPSPARSE(hipsparseCreateDnVec(&fs->dnVecDescr_X, m, fs->X, hipsparse_scalartype));
298:         PetscCallHIPSPARSE(hipsparseCreateDnVec(&fs->dnVecDescr_Y, m, fs->Y, hipsparse_scalartype));

300:         // Query buffer sizes for SpSV and then allocate buffers, temporarily assuming opA = HIPSPARSE_OPERATION_NON_TRANSPOSE
301:         PetscCallHIPSPARSE(hipsparseSpSV_createDescr(&fs->spsvDescr_L));
302:         PetscCallHIPSPARSE(hipsparseSpSV_bufferSize(handle, HIPSPARSE_OPERATION_NON_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_L, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, HIPSPARSE_SPSV_ALG_DEFAULT, fs->spsvDescr_L, &fs->spsvBufferSize_L));
303:         PetscCallHIPSPARSE(hipsparseSpSV_createDescr(&fs->spsvDescr_U));
304:         PetscCallHIPSPARSE(hipsparseSpSV_bufferSize(handle, HIPSPARSE_OPERATION_NON_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_U, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, HIPSPARSE_SPSV_ALG_DEFAULT, fs->spsvDescr_U, &fs->spsvBufferSize_U));
305:         PetscCallHIP(hipMalloc((void **)&fs->spsvBuffer_U, fs->spsvBufferSize_U));
306:         PetscCallHIP(hipMalloc((void **)&fs->spsvBuffer_L, fs->spsvBufferSize_L));

308:         // Record for reuse
309:         fs->csrRowPtr_h = Mi;
310:         fs->csrVal_h    = Ma;
311:         PetscCall(PetscFree(Mj));
312:       }
313:       // Copy the value
314:       Mi  = fs->csrRowPtr_h;
315:       Ma  = fs->csrVal_h;
316:       Mnz = Mi[m];
317:       for (PetscInt i = 0; i < m; i++) {
318:         PetscInt llen = Ai[i + 1] - Ai[i];
319:         PetscInt ulen = adiag[i] - adiag[i + 1];
320:         PetscCall(PetscArraycpy(Ma + Mi[i], Aa + Ai[i], llen));                           // entries of L
321:         Ma[Mi[i] + llen] = (MatScalar)1.0 / Aa[adiag[i]];                                 // recover the diagonal entry
322:         PetscCall(PetscArraycpy(Ma + Mi[i] + llen + 1, Aa + adiag[i + 1] + 1, ulen - 1)); // entries of U on the right of the diagonal
323:       }
324:       PetscCallHIP(hipMemcpyAsync(fs->csrVal, Ma, sizeof(*Ma) * Mnz, hipMemcpyHostToDevice, stream));
325:       PetscCall(PetscDeviceContextSynchronize(dctx));

327:       {
328:         // Do hipsparseSpSV_analysis(), which is numeric and requires valid and up-to-date matrix values
329:         PetscCallHIPSPARSE(hipsparseSpSV_analysis(handle, HIPSPARSE_OPERATION_NON_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_L, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, HIPSPARSE_SPSV_ALG_DEFAULT, fs->spsvDescr_L, fs->spsvBuffer_L));

331:         PetscCallHIPSPARSE(hipsparseSpSV_analysis(handle, HIPSPARSE_OPERATION_NON_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_U, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, HIPSPARSE_SPSV_ALG_DEFAULT, fs->spsvDescr_U, fs->spsvBuffer_U));
332:         fs->updatedSpSVAnalysis          = PETSC_TRUE;
333:         fs->updatedTransposeSpSVAnalysis = PETSC_FALSE;
334:       }
335:     }
336:     PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
337:   }
338:   PetscFunctionReturn(PETSC_SUCCESS);
339: }

341: static PetscErrorCode MatSeqAIJHIPSPARSEILUAnalysisAndCopyToGPU(Mat A)
342: {
343:   Mat_SeqAIJ                    *a                   = (Mat_SeqAIJ *)A->data;
344:   Mat_SeqAIJHIPSPARSETriFactors *hipsparseTriFactors = (Mat_SeqAIJHIPSPARSETriFactors *)A->spptr;
345:   IS                             isrow = a->row, isicol = a->icol;
346:   PetscBool                      row_identity, col_identity;
347:   PetscInt                       n = A->rmap->n;
348:   PetscDeviceContext             dctx;
349:   hipStream_t                    stream;

351:   PetscFunctionBegin;
352:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetHandles_(&dctx, &stream));
353:   PetscCheck(hipsparseTriFactors, PETSC_COMM_SELF, PETSC_ERR_COR, "Missing hipsparseTriFactors");
354:   PetscCall(MatSeqAIJHIPSPARSEBuildFactoredMatrix_LU(A));

356:   hipsparseTriFactors->nnz = a->nz;

358:   A->offloadmask = PETSC_OFFLOAD_BOTH; // factored matrix is sync'ed to GPU
359:   /* lower triangular indices */
360:   PetscCall(ISIdentity(isrow, &row_identity));
361:   if (!row_identity && !hipsparseTriFactors->rpermIndices) {
362:     const PetscInt *r;

364:     PetscCall(ISGetIndices(isrow, &r));
365:     hipsparseTriFactors->rpermIndices = new THRUSTINTARRAY(n);
366:     PetscCallHIP(hipMemcpyAsync(hipsparseTriFactors->rpermIndices->data().get(), r, (n) * sizeof(*r), hipMemcpyHostToDevice, stream));
367:     PetscCall(PetscDeviceContextSynchronize(dctx));
368:     PetscCall(ISRestoreIndices(isrow, &r));
369:     PetscCall(PetscLogCpuToGpu(n * sizeof(PetscInt)));
370:   }

372:   /* upper triangular indices */
373:   PetscCall(ISIdentity(isicol, &col_identity));
374:   if (!col_identity && !hipsparseTriFactors->cpermIndices) {
375:     const PetscInt *c;

377:     PetscCall(ISGetIndices(isicol, &c));
378:     hipsparseTriFactors->cpermIndices = new THRUSTINTARRAY(n);
379:     PetscCallHIP(hipMemcpyAsync(hipsparseTriFactors->cpermIndices->data().get(), c, (n) * sizeof(*c), hipMemcpyHostToDevice, stream));
380:     PetscCall(PetscDeviceContextSynchronize(dctx));
381:     PetscCall(ISRestoreIndices(isicol, &c));
382:     PetscCall(PetscLogCpuToGpu(n * sizeof(PetscInt)));
383:   }
384:   PetscFunctionReturn(PETSC_SUCCESS);
385: }

387: /*
388:   Affected rocSPARSE versions cache SpSV analysis with a descriptor-wide flag, so analysing an
389:   ordinary solve causes subsequent transpose analysis to be skipped. This occurs in the inspected
390:   ROCm releases from 5.0.0 through 7.2.0. Separate descriptors avoid sharing that flag while sharing
391:   the CSR arrays. Upstream fixes the cache to distinguish operation and fill mode:
392:   https://github.com/ROCm/rocm-libraries/pull/9295
393: */
394: static PetscErrorCode MatSeqAIJHIPSPARSECreateTransposeSolveMat(hipsparseSpMatDescr_t mat, hipsparseSpMatDescr_t *trans)
395: {
396:   int64_t              rows, cols, nnz;
397:   void                *rowptr, *colidx, *values;
398:   hipsparseIndexType_t rowtype, coltype;
399:   hipsparseIndexBase_t base;
400:   hipDataType          datatype;
401:   hipsparseFillMode_t  fill;
402:   hipsparseDiagType_t  diag;

404:   PetscFunctionBegin;
405:   PetscCallHIPSPARSE(hipsparseCsrGet(mat, &rows, &cols, &nnz, &rowptr, &colidx, &values, &rowtype, &coltype, &base, &datatype));
406:   PetscCallHIPSPARSE(hipsparseSpMatGetAttribute(mat, HIPSPARSE_SPMAT_FILL_MODE, &fill, sizeof(fill)));
407:   PetscCallHIPSPARSE(hipsparseSpMatGetAttribute(mat, HIPSPARSE_SPMAT_DIAG_TYPE, &diag, sizeof(diag)));
408:   PetscCallHIPSPARSE(hipsparseCreateCsr(trans, rows, cols, nnz, rowptr, colidx, values, rowtype, coltype, base, datatype));
409:   PetscCallHIPSPARSE(hipsparseSpMatSetAttribute(*trans, HIPSPARSE_SPMAT_FILL_MODE, &fill, sizeof(fill)));
410:   PetscCallHIPSPARSE(hipsparseSpMatSetAttribute(*trans, HIPSPARSE_SPMAT_DIAG_TYPE, &diag, sizeof(diag)));
411:   PetscFunctionReturn(PETSC_SUCCESS);
412: }

414: static PetscErrorCode MatSeqAIJHIPSPARSEBuildFactoredMatrix_Cholesky(Mat A)
415: {
416:   Mat_SeqAIJ                    *a  = static_cast<Mat_SeqAIJ *>(A->data);
417:   PetscInt                       m  = A->rmap->n;
418:   Mat_SeqAIJHIPSPARSETriFactors *fs = static_cast<Mat_SeqAIJHIPSPARSETriFactors *>(A->spptr);
419:   const PetscInt                *Ai = a->i, *Aj = a->j, *adiag;
420:   const MatScalar               *Aa = a->a;
421:   PetscInt                      *Mj, Mnz;
422:   PetscScalar                   *Ma, *D;
423:   PetscDeviceContext             dctx;
424:   hipStream_t                    stream;
425:   hipsparseHandle_t              handle;

427:   PetscFunctionBegin;
428:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetSparseHandles_(&dctx, &handle, &stream));
429:   {
430:     const SparsePointerModeGuard pointer_mode{handle, HIPSPARSE_POINTER_MODE_HOST};

432:     PetscCall(MatGetDiagonalMarkers_SeqAIJ(A, &adiag, NULL));
433:     if (A->offloadmask == PETSC_OFFLOAD_CPU) { // A's latest factors are on CPU
434:       if (!fs->csrRowPtr) {                    // Is this the first time we are doing setup? Use csrRowPtr since it is not null even m=0
435:         // Re-arrange the (skewed) factored matrix and put the result into M, a regular csr matrix on host.
436:         // See comments at MatICCFactorSymbolic_SeqAIJ() on the layout of the factored matrix (U) on host.
437:         Mnz = Ai[m]; // Unz (with the unit diagonal)
438:         PetscCall(PetscMalloc1(Mnz, &Ma));
439:         PetscCall(PetscMalloc1(Mnz, &Mj)); // Mj[] is temp
440:         PetscCall(PetscMalloc1(m, &D));    // the diagonal
441:         for (PetscInt i = 0; i < m; i++) {
442:           PetscInt ulen = Ai[i + 1] - Ai[i];
443:           Mj[Ai[i]]     = i;                                              // diagonal entry
444:           PetscCall(PetscArraycpy(Mj + Ai[i] + 1, Aj + Ai[i], ulen - 1)); // entries of U on the right of the diagonal
445:         }
446:         // Copy M (U) from host to device
447:         PetscCallHIP(hipMalloc(&fs->csrRowPtr, sizeof(*fs->csrRowPtr) * (m + 1)));
448:         PetscCallHIP(hipMalloc(&fs->csrColIdx, sizeof(*fs->csrColIdx) * Mnz));
449:         PetscCallHIP(hipMalloc(&fs->csrVal, sizeof(*fs->csrVal) * Mnz));
450:         PetscCallHIP(hipMalloc(&fs->diag, sizeof(*fs->diag) * m));
451:         PetscCallHIP(hipMemcpyAsync(fs->csrRowPtr, Ai, sizeof(*Ai) * (m + 1), hipMemcpyHostToDevice, stream));
452:         PetscCallHIP(hipMemcpyAsync(fs->csrColIdx, Mj, sizeof(*Mj) * Mnz, hipMemcpyHostToDevice, stream));
453:         PetscCall(PetscDeviceContextSynchronize(dctx));

455:         // Create descriptors for L, U. See https://docs.nvidia.com/cuda/cusparse/index.html#cusparseDiagType_t
456:         // cusparseDiagType_t: This type indicates if the matrix diagonal entries are unity. The diagonal elements are always
457:         // assumed to be present, but if CUSPARSE_DIAG_TYPE_UNIT is passed to an API routine, then the routine assumes that
458:         // all diagonal entries are unity and will not read or modify those entries. Note that in this case the routine
459:         // assumes the diagonal entries are equal to one, regardless of what those entries are actually set to in memory.
460:         hipsparseFillMode_t fillMode = HIPSPARSE_FILL_MODE_UPPER;
461:         hipsparseDiagType_t diagType = HIPSPARSE_DIAG_TYPE_UNIT; // U is unit diagonal

463:         PetscCallHIPSPARSE(hipsparseCreateCsr(&fs->spMatDescr_U, m, m, Mnz, fs->csrRowPtr, fs->csrColIdx, fs->csrVal, csrRowOffsetsType, csrColIndType, HIPSPARSE_INDEX_BASE_ZERO, hipsparse_scalartype));
464:         PetscCallHIPSPARSE(hipsparseSpMatSetAttribute(fs->spMatDescr_U, HIPSPARSE_SPMAT_FILL_MODE, &fillMode, sizeof(fillMode)));
465:         PetscCallHIPSPARSE(hipsparseSpMatSetAttribute(fs->spMatDescr_U, HIPSPARSE_SPMAT_DIAG_TYPE, &diagType, sizeof(diagType)));

467:         // Allocate work vectors in SpSv
468:         PetscCallHIP(hipMalloc((void **)&fs->X, sizeof(*fs->X) * m));
469:         PetscCallHIP(hipMalloc((void **)&fs->Y, sizeof(*fs->Y) * m));

471:         PetscCallHIPSPARSE(hipsparseCreateDnVec(&fs->dnVecDescr_X, m, fs->X, hipsparse_scalartype));
472:         PetscCallHIPSPARSE(hipsparseCreateDnVec(&fs->dnVecDescr_Y, m, fs->Y, hipsparse_scalartype));

474:         // Query buffer sizes for SpSV and then allocate buffers
475:         PetscCallHIPSPARSE(hipsparseSpSV_createDescr(&fs->spsvDescr_U));
476:         PetscCallHIPSPARSE(hipsparseSpSV_bufferSize(handle, HIPSPARSE_OPERATION_NON_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_U, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, HIPSPARSE_SPSV_ALG_DEFAULT, fs->spsvDescr_U, &fs->spsvBufferSize_U));
477:         PetscCallHIP(hipMalloc((void **)&fs->spsvBuffer_U, fs->spsvBufferSize_U));

479:         PetscCall(MatSeqAIJHIPSPARSECreateTransposeSolveMat(fs->spMatDescr_U, &fs->spMatDescr_Ut));
480:         PetscCallHIPSPARSE(hipsparseSpSV_createDescr(&fs->spsvDescr_Ut));
481:         PetscCallHIPSPARSE(hipsparseSpSV_bufferSize(handle, HIPSPARSE_OPERATION_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_Ut, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, HIPSPARSE_SPSV_ALG_DEFAULT, fs->spsvDescr_Ut, &fs->spsvBufferSize_Ut));
482:         PetscCallHIP(hipMalloc((void **)&fs->spsvBuffer_Ut, fs->spsvBufferSize_Ut));

484:         // Record for reuse
485:         fs->csrVal_h = Ma;
486:         fs->diag_h   = D;
487:         PetscCall(PetscFree(Mj));
488:       }
489:       // Copy the value
490:       Ma  = fs->csrVal_h;
491:       D   = fs->diag_h;
492:       Mnz = Ai[m];
493:       for (PetscInt i = 0; i < m; i++) {
494:         D[i]      = Aa[adiag[i]];   // actually Aa[adiag[i]] is the inverse of the diagonal
495:         Ma[Ai[i]] = (MatScalar)1.0; // set the unit diagonal, which is cosmetic since cusparse does not really read it given CUSPARSE_DIAG_TYPE_UNIT
496:         for (PetscInt k = 0; k < Ai[i + 1] - Ai[i] - 1; k++) Ma[Ai[i] + 1 + k] = -Aa[Ai[i] + k];
497:       }
498:       PetscCallHIP(hipMemcpyAsync(fs->csrVal, Ma, sizeof(*Ma) * Mnz, hipMemcpyHostToDevice, stream));
499:       PetscCallHIP(hipMemcpyAsync(fs->diag, D, sizeof(*D) * m, hipMemcpyHostToDevice, stream));
500:       PetscCall(PetscDeviceContextSynchronize(dctx));

502:       {
503:         // Do hipsparseSpSV_analysis(), which is numeric and requires valid and up-to-date matrix values
504:         PetscCallHIPSPARSE(hipsparseSpSV_analysis(handle, HIPSPARSE_OPERATION_NON_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_U, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, HIPSPARSE_SPSV_ALG_DEFAULT, fs->spsvDescr_U, fs->spsvBuffer_U));
505:         PetscCallHIPSPARSE(hipsparseSpSV_analysis(handle, HIPSPARSE_OPERATION_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_Ut, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, HIPSPARSE_SPSV_ALG_DEFAULT, fs->spsvDescr_Ut, fs->spsvBuffer_Ut));
506:         fs->updatedSpSVAnalysis = PETSC_TRUE;
507:       }
508:     }
509:     PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
510:   }
511:   PetscFunctionReturn(PETSC_SUCCESS);
512: }

514: // Solve Ut D U x = b
515: static PetscErrorCode MatSolve_SeqAIJHIPSPARSE_Cholesky(Mat A, Vec b, Vec x)
516: {
517:   Mat_SeqAIJHIPSPARSETriFactors        *fs  = static_cast<Mat_SeqAIJHIPSPARSETriFactors *>(A->spptr);
518:   Mat_SeqAIJ                           *aij = static_cast<Mat_SeqAIJ *>(A->data);
519:   const PetscScalar                    *barray;
520:   PetscScalar                          *xarray;
521:   thrust::device_ptr<const PetscScalar> bGPU;
522:   thrust::device_ptr<PetscScalar>       xGPU;
523:   const hipsparseSpSVAlg_t              alg = HIPSPARSE_SPSV_ALG_DEFAULT;
524:   PetscInt                              m   = A->rmap->n;
525:   PetscDeviceContext                    dctx;
526:   hipStream_t                           stream;
527:   hipsparseHandle_t                     handle;

529:   PetscFunctionBegin;
530:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetSparseHandles_(&dctx, &handle, &stream));
531:   {
532:     const SparsePointerModeGuard pointer_mode{handle, HIPSPARSE_POINTER_MODE_HOST};

534:     PetscCall(PetscLogGpuTimeBegin());
535:     PetscCall(VecHIPGetArrayWrite(x, &xarray));
536:     PetscCall(VecHIPGetArrayRead(b, &barray));
537:     xGPU = thrust::device_pointer_cast(xarray);
538:     bGPU = thrust::device_pointer_cast(barray);

540:     // Reorder b with the row permutation if needed, and wrap the result in fs->X
541:     if (fs->rpermIndices)
542:       PetscCallThrust(thrust::copy(thrust::device.on(stream), thrust::make_permutation_iterator(bGPU, fs->rpermIndices->begin()), thrust::make_permutation_iterator(bGPU, fs->rpermIndices->end()), thrust::device_pointer_cast(fs->X)));

544:     PetscCallHIPSPARSE(hipsparseDnVecSetValues(fs->dnVecDescr_X, fs->rpermIndices ? fs->X : (void *)barray));

546:     // Solve Ut Y = X
547:     PetscCallHIPSPARSE(hipsparseDnVecSetValues(fs->dnVecDescr_Y, fs->Y));
548: #if PETSC_PKG_HIP_VERSION_EQ(5, 6, 0) || PETSC_PKG_HIP_VERSION_GE(6, 0, 0)
549:     PetscCallHIPSPARSE(hipsparseSpSV_solve(handle, HIPSPARSE_OPERATION_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_Ut, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, alg, fs->spsvDescr_Ut));
550: #else
551:     PetscCallHIPSPARSE(hipsparseSpSV_solve(handle, HIPSPARSE_OPERATION_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_Ut, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, alg, fs->spsvDescr_Ut, fs->spsvBuffer_Ut));
552: #endif

554:     // Solve diag(D) Z = Y. Actually just do Y = Y*D since D is already inverted in MatCholeskyFactorNumeric_SeqAIJ().
555:     // It is basically a vector element-wise multiplication, but cublas does not have it!
556:     auto multiplies = thrust::multiplies<PetscScalar>();
557:     PetscCallThrust(thrust::transform(thrust::device.on(stream), thrust::device_pointer_cast(fs->Y), thrust::device_pointer_cast(fs->Y + m), thrust::device_pointer_cast(fs->diag), thrust::device_pointer_cast(fs->Y), multiplies));

559:     // Solve U X = Y
560:     PetscCallHIPSPARSE(hipsparseDnVecSetValues(fs->dnVecDescr_X, fs->cpermIndices ? fs->X : xarray)); // if need to permute, we need to use the intermediate buffer X

562: #if PETSC_PKG_HIP_VERSION_EQ(5, 6, 0) || PETSC_PKG_HIP_VERSION_GE(6, 0, 0)
563:     PetscCallHIPSPARSE(hipsparseSpSV_solve(handle, HIPSPARSE_OPERATION_NON_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_U, fs->dnVecDescr_Y, fs->dnVecDescr_X, hipsparse_scalartype, alg, fs->spsvDescr_U));
564: #else
565:     PetscCallHIPSPARSE(hipsparseSpSV_solve(handle, HIPSPARSE_OPERATION_NON_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_U, fs->dnVecDescr_Y, fs->dnVecDescr_X, hipsparse_scalartype, alg, fs->spsvDescr_U, fs->spsvBuffer_U));
566: #endif

568:     // Reorder X with the column permutation if needed, and put the result back to x
569:     if (fs->cpermIndices)
570:       PetscCallThrust(thrust::copy(thrust::device.on(stream), thrust::make_permutation_iterator(thrust::device_pointer_cast(fs->X), fs->cpermIndices->begin()), thrust::make_permutation_iterator(thrust::device_pointer_cast(fs->X + m), fs->cpermIndices->end()), xGPU));

572:     PetscCall(VecHIPRestoreArrayRead(b, &barray));
573:     PetscCall(VecHIPRestoreArrayWrite(x, &xarray));
574:     PetscCall(PetscLogGpuTimeEnd());
575:     PetscCall(PetscLogGpuFlops(4.0 * aij->nz - A->rmap->n));
576:     PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
577:   }
578:   PetscFunctionReturn(PETSC_SUCCESS);
579: }

581: static PetscErrorCode MatSeqAIJHIPSPARSEICCAnalysisAndCopyToGPU(Mat A)
582: {
583:   Mat_SeqAIJ                    *a                   = (Mat_SeqAIJ *)A->data;
584:   Mat_SeqAIJHIPSPARSETriFactors *hipsparseTriFactors = (Mat_SeqAIJHIPSPARSETriFactors *)A->spptr;
585:   IS                             ip                  = a->row;
586:   PetscBool                      perm_identity;
587:   PetscInt                       n = A->rmap->n;
588:   PetscDeviceContext             dctx;
589:   hipStream_t                    stream;

591:   PetscFunctionBegin;
592:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetHandles_(&dctx, &stream));
593:   PetscCheck(hipsparseTriFactors, PETSC_COMM_SELF, PETSC_ERR_COR, "Missing hipsparseTriFactors");

595:   PetscCall(MatSeqAIJHIPSPARSEBuildFactoredMatrix_Cholesky(A));
596:   hipsparseTriFactors->nnz = (a->nz - n) * 2 + n;

598:   A->offloadmask = PETSC_OFFLOAD_BOTH;

600:   /* lower triangular indices */
601:   PetscCall(ISIdentity(ip, &perm_identity));
602:   if (!perm_identity) {
603:     IS              iip;
604:     const PetscInt *irip, *rip;

606:     PetscCall(ISInvertPermutation(ip, PETSC_DECIDE, &iip));
607:     PetscCall(ISGetIndices(iip, &irip));
608:     PetscCall(ISGetIndices(ip, &rip));
609:     hipsparseTriFactors->rpermIndices = new THRUSTINTARRAY(n);
610:     PetscCallHIP(hipMemcpyAsync(hipsparseTriFactors->rpermIndices->data().get(), rip, (n) * sizeof(*rip), hipMemcpyHostToDevice, stream));
611:     hipsparseTriFactors->cpermIndices = new THRUSTINTARRAY(n);
612:     PetscCallHIP(hipMemcpyAsync(hipsparseTriFactors->cpermIndices->data().get(), irip, (n) * sizeof(*irip), hipMemcpyHostToDevice, stream));
613:     PetscCall(PetscDeviceContextSynchronize(dctx));
614:     PetscCall(ISRestoreIndices(iip, &irip));
615:     PetscCall(ISDestroy(&iip));
616:     PetscCall(ISRestoreIndices(ip, &rip));
617:     PetscCall(PetscLogCpuToGpu(2. * n * sizeof(PetscInt)));
618:   }
619:   PetscFunctionReturn(PETSC_SUCCESS);
620: }

622: static PetscErrorCode MatCholeskyFactorNumeric_SeqAIJHIPSPARSE(Mat B, Mat A, const MatFactorInfo *info)
623: {
624:   PetscFunctionBegin;
625:   PetscCall(MatSeqAIJHIPSPARSECopyFromGPU(A));
626:   PetscCall(MatCholeskyFactorNumeric_SeqAIJ(B, A, info));
627:   B->offloadmask            = PETSC_OFFLOAD_CPU;
628:   B->ops->solve             = MatSolve_SeqAIJHIPSPARSE_Cholesky;
629:   B->ops->solvetranspose    = MatSolve_SeqAIJHIPSPARSE_Cholesky; // since symmetric
630:   B->ops->matsolve          = NULL;
631:   B->ops->matsolvetranspose = NULL;
632:   /* get the triangular factors */
633:   PetscCall(MatSeqAIJHIPSPARSEICCAnalysisAndCopyToGPU(B));
634:   PetscFunctionReturn(PETSC_SUCCESS);
635: }

637: static PetscErrorCode MatSeqAIJHIPSPARSEFormExplicitTranspose(Mat A)
638: {
639:   Mat_SeqAIJHIPSPARSE           *hipsparsestruct = (Mat_SeqAIJHIPSPARSE *)A->spptr;
640:   Mat_SeqAIJHIPSPARSEMultStruct *matstruct, *matstructT;
641:   Mat_SeqAIJ                    *a = (Mat_SeqAIJ *)A->data;
642:   hipsparseIndexBase_t           indexBase;
643:   PetscDeviceContext             dctx;
644:   hipStream_t                    stream;

646:   PetscFunctionBegin;
647:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetHandles_(&dctx, &stream));
648:   PetscCall(MatSeqAIJHIPSPARSECopyToGPU(A));
649:   matstruct = (Mat_SeqAIJHIPSPARSEMultStruct *)hipsparsestruct->mat;
650:   PetscCheck(matstruct, PETSC_COMM_SELF, PETSC_ERR_GPU, "Missing mat struct");
651:   matstructT = (Mat_SeqAIJHIPSPARSEMultStruct *)hipsparsestruct->matTranspose;
652:   PetscCheck(!A->transupdated || matstructT, PETSC_COMM_SELF, PETSC_ERR_GPU, "Missing matTranspose struct");
653:   if (A->transupdated) PetscFunctionReturn(PETSC_SUCCESS);
654:   PetscCall(PetscLogEventBegin(MAT_HIPSPARSEGenerateTranspose, A, 0, 0, 0));
655:   PetscCall(PetscLogGpuTimeBegin());
656:   if (hipsparsestruct->format != MAT_HIPSPARSE_CSR) PetscCall(MatSeqAIJHIPSPARSEInvalidateTranspose(A, PETSC_TRUE));
657:   if (!hipsparsestruct->matTranspose) { /* create hipsparse matrix */
658:     matstructT = new Mat_SeqAIJHIPSPARSEMultStruct;
659:     PetscCallHIPSPARSE(hipsparseCreateMatDescr(&matstructT->descr));
660:     indexBase = hipsparseGetMatIndexBase(matstruct->descr);
661:     PetscCallHIPSPARSE(hipsparseSetMatIndexBase(matstructT->descr, indexBase));
662:     PetscCallHIPSPARSE(hipsparseSetMatType(matstructT->descr, HIPSPARSE_MATRIX_TYPE_GENERAL));

664:     /* set alpha and beta */
665:     PetscCallHIP(hipMalloc((void **)&matstructT->alpha_one, sizeof(PetscScalar)));
666:     PetscCallHIP(hipMalloc((void **)&matstructT->beta_zero, sizeof(PetscScalar)));
667:     PetscCallHIP(hipMalloc((void **)&matstructT->beta_one, sizeof(PetscScalar)));
668:     PetscCallHIP(hipMemcpyAsync(matstructT->alpha_one, &PETSC_HIPSPARSE_ONE, sizeof(PetscScalar), hipMemcpyHostToDevice, stream));
669:     PetscCallHIP(hipMemcpyAsync(matstructT->beta_zero, &PETSC_HIPSPARSE_ZERO, sizeof(PetscScalar), hipMemcpyHostToDevice, stream));
670:     PetscCallHIP(hipMemcpyAsync(matstructT->beta_one, &PETSC_HIPSPARSE_ONE, sizeof(PetscScalar), hipMemcpyHostToDevice, stream));

672:     if (hipsparsestruct->format == MAT_HIPSPARSE_CSR) {
673:       CsrMatrix *matrixT      = new CsrMatrix;
674:       matstructT->mat         = matrixT;
675:       matrixT->num_rows       = A->cmap->n;
676:       matrixT->num_cols       = A->rmap->n;
677:       matrixT->num_entries    = a->nz;
678:       matrixT->row_offsets    = new THRUSTINTARRAY(matrixT->num_rows + 1);
679:       matrixT->column_indices = new THRUSTINTARRAY(a->nz);
680:       matrixT->values         = new THRUSTARRAY(a->nz);

682:       if (!hipsparsestruct->rowoffsets_gpu) hipsparsestruct->rowoffsets_gpu = new THRUSTINTARRAY(A->rmap->n + 1);
683:       PetscCallHIP(hipMemcpyAsync(hipsparsestruct->rowoffsets_gpu->data().get(), a->i, (A->rmap->n + 1) * sizeof(*a->i), hipMemcpyHostToDevice, stream));
684:       PetscCall(PetscDeviceContextSynchronize(dctx));
685:       PetscCallHIPSPARSE(hipsparseCreateCsr(&matstructT->matDescr, matrixT->num_rows, matrixT->num_cols, matrixT->num_entries, matrixT->row_offsets->data().get(), matrixT->column_indices->data().get(), matrixT->values->data().get(), csrRowOffsetsType, csrColIndType, indexBase, hipsparse_scalartype));
686:     } else if (hipsparsestruct->format == MAT_HIPSPARSE_ELL || hipsparsestruct->format == MAT_HIPSPARSE_HYB) {
687:       SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "MAT_HIPSPARSE_ELL and MAT_HIPSPARSE_HYB are not supported");
688:     }
689:   }
690:   if (hipsparsestruct->format == MAT_HIPSPARSE_CSR) { /* transpose mat struct may be already present, update data */
691:     CsrMatrix *matrix  = (CsrMatrix *)matstruct->mat;
692:     CsrMatrix *matrixT = (CsrMatrix *)matstructT->mat;
693:     PetscCheck(matrix, PETSC_COMM_SELF, PETSC_ERR_GPU, "Missing CsrMatrix");
694:     PetscCheck(matrix->row_offsets, PETSC_COMM_SELF, PETSC_ERR_GPU, "Missing CsrMatrix rows");
695:     PetscCheck(matrix->column_indices, PETSC_COMM_SELF, PETSC_ERR_GPU, "Missing CsrMatrix cols");
696:     PetscCheck(matrix->values, PETSC_COMM_SELF, PETSC_ERR_GPU, "Missing CsrMatrix values");
697:     PetscCheck(matrixT, PETSC_COMM_SELF, PETSC_ERR_GPU, "Missing CsrMatrixT");
698:     PetscCheck(matrixT->row_offsets, PETSC_COMM_SELF, PETSC_ERR_GPU, "Missing CsrMatrixT rows");
699:     PetscCheck(matrixT->column_indices, PETSC_COMM_SELF, PETSC_ERR_GPU, "Missing CsrMatrixT cols");
700:     PetscCheck(matrixT->values, PETSC_COMM_SELF, PETSC_ERR_GPU, "Missing CsrMatrixT values");
701:     if (!hipsparsestruct->rowoffsets_gpu) { /* this may be absent when we did not construct the transpose with csr2csc */
702:       hipsparsestruct->rowoffsets_gpu = new THRUSTINTARRAY(A->rmap->n + 1);
703:       PetscCallHIP(hipMemcpyAsync(hipsparsestruct->rowoffsets_gpu->data().get(), a->i, (A->rmap->n + 1) * sizeof(*a->i), hipMemcpyHostToDevice, stream));
704:       PetscCall(PetscDeviceContextSynchronize(dctx));
705:       PetscCall(PetscLogCpuToGpu((A->rmap->n + 1) * sizeof(PetscInt)));
706:     }
707:     if (!hipsparsestruct->csr2csc_i) { // not using hipsparseCsr2cscEx2() because it requires 32-bit indices
708:       THRUSTINTARRAY row_indices(matrix->num_entries);

710:       // Transpose the matrix via COO, i.e., by putting the row indices in column_indices[] and the column indices in row_indices[]
711:       hipsparsestruct->csr2csc_i = new THRUSTINTARRAY(matrix->num_entries); // will store the matrix to matrixT permutation, i.e., entry matrixT[i] is matrix[csr2csc_i[i]]
712:       PetscCallThrust(thrust::sequence(thrust::device.on(stream), hipsparsestruct->csr2csc_i->begin(), hipsparsestruct->csr2csc_i->end()));
713:       PetscCallThrust(thrust::for_each(thrust::device.on(stream), thrust::counting_iterator<PetscInt>(0), thrust::counting_iterator<PetscInt>(A->rmap->n), Csr2coo(hipsparsestruct->rowoffsets_gpu->data().get(), matrixT->column_indices->data().get())));
714:       PetscCallThrust(thrust::copy(thrust::device.on(stream), matrix->column_indices->begin(), matrix->column_indices->end(), row_indices.begin()));
715:       // Sort the COO by row then column, and get the permutation csr2csc_i[]
716:       PetscCallThrust(thrust::sort_by_key(thrust::device.on(stream), thrust::make_zip_iterator(thrust::make_tuple(row_indices.begin(), matrixT->column_indices->begin())),
717:                                           thrust::make_zip_iterator(thrust::make_tuple(row_indices.end(), matrixT->column_indices->end())), hipsparsestruct->csr2csc_i->begin()));
718:       // Finalize matrixT's row_offsets by looking up row_indices[]
719:       PetscCallThrust(thrust::lower_bound(thrust::device.on(stream), row_indices.begin(), row_indices.end(), thrust::counting_iterator<PetscInt>(0), thrust::counting_iterator<PetscInt>(A->cmap->n + 1), matrixT->row_offsets->begin()));
720:     }
721:     PetscCallThrust(thrust::gather(thrust::device.on(stream), hipsparsestruct->csr2csc_i->begin(), hipsparsestruct->csr2csc_i->end(), matrix->values->begin(), matrixT->values->begin()));
722:   }
723:   PetscCall(PetscLogGpuTimeEnd());
724:   PetscCall(PetscLogEventEnd(MAT_HIPSPARSEGenerateTranspose, A, 0, 0, 0));
725:   /* the compressed row indices is not used for matTranspose */
726:   matstructT->cprowIndices = NULL;
727:   /* assign the pointer */
728:   ((Mat_SeqAIJHIPSPARSE *)A->spptr)->matTranspose = matstructT;
729:   A->transupdated                                 = PETSC_TRUE;
730:   PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
731:   PetscFunctionReturn(PETSC_SUCCESS);
732: }

734: static PetscErrorCode MatSolve_SeqAIJHIPSPARSE_LU(Mat A, Vec b, Vec x)
735: {
736:   const PetscScalar                    *barray;
737:   PetscScalar                          *xarray;
738:   thrust::device_ptr<const PetscScalar> bGPU;
739:   thrust::device_ptr<PetscScalar>       xGPU;
740:   Mat_SeqAIJHIPSPARSETriFactors        *fs  = static_cast<Mat_SeqAIJHIPSPARSETriFactors *>(A->spptr);
741:   const Mat_SeqAIJ                     *aij = static_cast<Mat_SeqAIJ *>(A->data);
742:   const hipsparseOperation_t            op  = HIPSPARSE_OPERATION_NON_TRANSPOSE;
743:   const hipsparseSpSVAlg_t              alg = HIPSPARSE_SPSV_ALG_DEFAULT;
744:   PetscInt                              m   = A->rmap->n;
745:   PetscDeviceContext                    dctx;
746:   hipStream_t                           stream;
747:   hipsparseHandle_t                     handle;

749:   PetscFunctionBegin;
750:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetSparseHandles_(&dctx, &handle, &stream));
751:   {
752:     const SparsePointerModeGuard pointer_mode{handle, HIPSPARSE_POINTER_MODE_HOST};

754:     PetscCall(PetscLogGpuTimeBegin());
755:     PetscCall(VecHIPGetArrayWrite(x, &xarray));
756:     PetscCall(VecHIPGetArrayRead(b, &barray));
757:     xGPU = thrust::device_pointer_cast(xarray);
758:     bGPU = thrust::device_pointer_cast(barray);

760:     // Reorder b with the row permutation if needed, and wrap the result in fs->X
761:     if (fs->rpermIndices)
762:       PetscCallThrust(thrust::copy(thrust::device.on(stream), thrust::make_permutation_iterator(bGPU, fs->rpermIndices->begin()), thrust::make_permutation_iterator(bGPU, fs->rpermIndices->end()), thrust::device_pointer_cast(fs->X)));

764:     PetscCallHIPSPARSE(hipsparseDnVecSetValues(fs->dnVecDescr_X, fs->rpermIndices ? fs->X : (void *)barray));

766:     // Solve L Y = X
767:     PetscCallHIPSPARSE(hipsparseDnVecSetValues(fs->dnVecDescr_Y, fs->Y));
768:     // Note that hipsparseSpSV_solve() secretly uses the external buffer used in hipsparseSpSV_analysis()!

770: #if PETSC_PKG_HIP_VERSION_EQ(5, 6, 0) || PETSC_PKG_HIP_VERSION_GE(6, 0, 0)
771:     PetscCallHIPSPARSE(hipsparseSpSV_solve(handle, op, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_L, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, alg, fs->spsvDescr_L));
772: #else
773:     PetscCallHIPSPARSE(hipsparseSpSV_solve(handle, op, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_L, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, alg, fs->spsvDescr_L, fs->spsvBuffer_L));
774: #endif

776:     // Solve U X = Y
777:     PetscCallHIPSPARSE(hipsparseDnVecSetValues(fs->dnVecDescr_X, fs->cpermIndices ? fs->X : xarray));

779: #if PETSC_PKG_HIP_VERSION_EQ(5, 6, 0) || PETSC_PKG_HIP_VERSION_GE(6, 0, 0)
780:     PetscCallHIPSPARSE(hipsparseSpSV_solve(handle, op, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_U, fs->dnVecDescr_Y, fs->dnVecDescr_X, hipsparse_scalartype, alg, fs->spsvDescr_U));
781: #else
782:     PetscCallHIPSPARSE(hipsparseSpSV_solve(handle, op, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_U, fs->dnVecDescr_Y, fs->dnVecDescr_X, hipsparse_scalartype, alg, fs->spsvDescr_U, fs->spsvBuffer_U));
783: #endif

785:     // Reorder X with the column permutation if needed, and put the result back to x
786:     if (fs->cpermIndices)
787:       PetscCallThrust(thrust::copy(thrust::device.on(stream), thrust::make_permutation_iterator(thrust::device_pointer_cast(fs->X), fs->cpermIndices->begin()), thrust::make_permutation_iterator(thrust::device_pointer_cast(fs->X + m), fs->cpermIndices->end()), xGPU));
788:     PetscCall(VecHIPRestoreArrayRead(b, &barray));
789:     PetscCall(VecHIPRestoreArrayWrite(x, &xarray));
790:     PetscCall(PetscLogGpuTimeEnd());
791:     PetscCall(PetscLogGpuFlops(2.0 * aij->nz - m));
792:     PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
793:   }
794:   PetscFunctionReturn(PETSC_SUCCESS);
795: }

797: static PetscErrorCode MatSolveTranspose_SeqAIJHIPSPARSE_LU(Mat A, Vec b, Vec x)
798: {
799:   Mat_SeqAIJHIPSPARSETriFactors        *fs  = static_cast<Mat_SeqAIJHIPSPARSETriFactors *>(A->spptr);
800:   Mat_SeqAIJ                           *aij = static_cast<Mat_SeqAIJ *>(A->data);
801:   const PetscScalar                    *barray;
802:   PetscScalar                          *xarray;
803:   thrust::device_ptr<const PetscScalar> bGPU;
804:   thrust::device_ptr<PetscScalar>       xGPU;
805:   const hipsparseOperation_t            opA = HIPSPARSE_OPERATION_TRANSPOSE;
806:   const hipsparseSpSVAlg_t              alg = HIPSPARSE_SPSV_ALG_DEFAULT;
807:   PetscInt                              m   = A->rmap->n;
808:   PetscDeviceContext                    dctx;
809:   hipStream_t                           stream;
810:   hipsparseHandle_t                     handle;

812:   PetscFunctionBegin;
813:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetSparseHandles_(&dctx, &handle, &stream));
814:   {
815:     const SparsePointerModeGuard pointer_mode{handle, HIPSPARSE_POINTER_MODE_HOST};

817:     PetscCall(PetscLogGpuTimeBegin());
818:     if (!fs->createdTransposeSpSVDescr) { // Call MatSolveTranspose() for the first time
819:       PetscCall(MatSeqAIJHIPSPARSECreateTransposeSolveMat(fs->spMatDescr_L, &fs->spMatDescr_Lt));
820:       PetscCall(MatSeqAIJHIPSPARSECreateTransposeSolveMat(fs->spMatDescr_U, &fs->spMatDescr_Ut));
821:       PetscCallHIPSPARSE(hipsparseSpSV_createDescr(&fs->spsvDescr_Lt));
822:       PetscCallHIPSPARSE(hipsparseSpSV_bufferSize(handle, opA, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_Lt, /* The matrix is still L. We only do transpose solve with it */
823:                                                   fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, alg, fs->spsvDescr_Lt, &fs->spsvBufferSize_Lt));

825:       PetscCallHIPSPARSE(hipsparseSpSV_createDescr(&fs->spsvDescr_Ut));
826:       PetscCallHIPSPARSE(hipsparseSpSV_bufferSize(handle, opA, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_Ut, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, alg, fs->spsvDescr_Ut, &fs->spsvBufferSize_Ut));
827:       PetscCallHIP(hipMalloc((void **)&fs->spsvBuffer_Lt, fs->spsvBufferSize_Lt));
828:       PetscCallHIP(hipMalloc((void **)&fs->spsvBuffer_Ut, fs->spsvBufferSize_Ut));
829:       fs->createdTransposeSpSVDescr = PETSC_TRUE;
830:     }

832:     if (!fs->updatedTransposeSpSVAnalysis) {
833:       PetscCallHIPSPARSE(hipsparseSpSV_analysis(handle, opA, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_Lt, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, alg, fs->spsvDescr_Lt, fs->spsvBuffer_Lt));

835:       PetscCallHIPSPARSE(hipsparseSpSV_analysis(handle, opA, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_Ut, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, alg, fs->spsvDescr_Ut, fs->spsvBuffer_Ut));
836:       fs->updatedTransposeSpSVAnalysis = PETSC_TRUE;
837:     }

839:     PetscCall(VecHIPGetArrayWrite(x, &xarray));
840:     PetscCall(VecHIPGetArrayRead(b, &barray));
841:     xGPU = thrust::device_pointer_cast(xarray);
842:     bGPU = thrust::device_pointer_cast(barray);

844:     // Reorder b with the row permutation if needed, and wrap the result in fs->X
845:     if (fs->rpermIndices)
846:       PetscCallThrust(thrust::copy(thrust::device.on(stream), thrust::make_permutation_iterator(bGPU, fs->rpermIndices->begin()), thrust::make_permutation_iterator(bGPU, fs->rpermIndices->end()), thrust::device_pointer_cast(fs->X)));

848:     PetscCallHIPSPARSE(hipsparseDnVecSetValues(fs->dnVecDescr_X, fs->rpermIndices ? fs->X : (void *)barray));

850:     // Solve Ut Y = X
851:     PetscCallHIPSPARSE(hipsparseDnVecSetValues(fs->dnVecDescr_Y, fs->Y));
852: #if PETSC_PKG_HIP_VERSION_EQ(5, 6, 0) || PETSC_PKG_HIP_VERSION_GE(6, 0, 0)
853:     PetscCallHIPSPARSE(hipsparseSpSV_solve(handle, opA, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_Ut, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, alg, fs->spsvDescr_Ut));
854: #else
855:     PetscCallHIPSPARSE(hipsparseSpSV_solve(handle, opA, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_Ut, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, alg, fs->spsvDescr_Ut, fs->spsvBuffer_Ut));
856: #endif

858:     // Solve Lt X = Y
859:     PetscCallHIPSPARSE(hipsparseDnVecSetValues(fs->dnVecDescr_X, fs->cpermIndices ? fs->X : xarray)); // if need to permute, we need to use the intermediate buffer X

861: #if PETSC_PKG_HIP_VERSION_EQ(5, 6, 0) || PETSC_PKG_HIP_VERSION_GE(6, 0, 0)
862:     PetscCallHIPSPARSE(hipsparseSpSV_solve(handle, opA, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_Lt, fs->dnVecDescr_Y, fs->dnVecDescr_X, hipsparse_scalartype, alg, fs->spsvDescr_Lt));
863: #else
864:     PetscCallHIPSPARSE(hipsparseSpSV_solve(handle, opA, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_Lt, fs->dnVecDescr_Y, fs->dnVecDescr_X, hipsparse_scalartype, alg, fs->spsvDescr_Lt, fs->spsvBuffer_Lt));
865: #endif

867:     // Reorder X with the column permutation if needed, and put the result back to x
868:     if (fs->cpermIndices)
869:       PetscCallThrust(thrust::copy(thrust::device.on(stream), thrust::make_permutation_iterator(thrust::device_pointer_cast(fs->X), fs->cpermIndices->begin()), thrust::make_permutation_iterator(thrust::device_pointer_cast(fs->X + m), fs->cpermIndices->end()), xGPU));

871:     PetscCall(VecHIPRestoreArrayRead(b, &barray));
872:     PetscCall(VecHIPRestoreArrayWrite(x, &xarray));
873:     PetscCall(PetscLogGpuTimeEnd());
874:     PetscCall(PetscLogGpuFlops(2.0 * aij->nz - A->rmap->n));
875:     PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
876:   }
877:   PetscFunctionReturn(PETSC_SUCCESS);
878: }

880: static PetscErrorCode MatILUFactorNumeric_SeqAIJHIPSPARSE_ILU0(Mat fact, Mat A, const MatFactorInfo *info)
881: {
882:   Mat_SeqAIJHIPSPARSETriFactors *fs    = (Mat_SeqAIJHIPSPARSETriFactors *)fact->spptr;
883:   Mat_SeqAIJ                    *aij   = (Mat_SeqAIJ *)fact->data;
884:   Mat_SeqAIJHIPSPARSE           *Acusp = (Mat_SeqAIJHIPSPARSE *)A->spptr;
885:   CsrMatrix                     *Acsr;
886:   PetscInt                       m, nz;
887:   PetscBool                      flg;
888:   PetscDeviceContext             dctx;
889:   hipStream_t                    stream;
890:   hipsparseHandle_t              handle;

892:   PetscFunctionBegin;
893:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetSparseHandles_(&dctx, &handle, &stream));
894:   {
895:     const SparsePointerModeGuard pointer_mode{handle, HIPSPARSE_POINTER_MODE_HOST};

897:     if (PetscDefined(USE_DEBUG)) {
898:       PetscCall(PetscObjectTypeCompare((PetscObject)A, MATSEQAIJHIPSPARSE, &flg));
899:       PetscCheck(flg, PetscObjectComm((PetscObject)A), PETSC_ERR_GPU, "Expected MATSEQAIJHIPSPARSE, but input is %s", ((PetscObject)A)->type_name);
900:     }

902:     /* Copy A's value to fact */
903:     m  = fact->rmap->n;
904:     nz = aij->nz;
905:     PetscCall(MatSeqAIJHIPSPARSECopyToGPU(A));
906:     Acsr = (CsrMatrix *)Acusp->mat->mat;
907:     PetscCallHIP(hipMemcpyAsync(fs->csrVal, Acsr->values->data().get(), sizeof(PetscScalar) * nz, hipMemcpyDeviceToDevice, stream));

909:     PetscCall(PetscLogGpuTimeBegin());
910:     /* Factorize fact inplace */
911:     if (m)
912:       PetscCallHIPSPARSE(hipsparseXcsrilu02(handle, m, nz, /* hipsparseXcsrilu02 errors out with empty matrices (m=0) */
913:                                             fs->matDescr_M, fs->csrVal, fs->csrRowPtr32, fs->csrColIdx32, fs->ilu0Info_M, fs->policy_M, fs->factBuffer_M));
914:     if (PetscDefined(USE_DEBUG)) {
915:       int               numerical_zero;
916:       hipsparseStatus_t status;
917:       status = hipsparseXcsrilu02_zeroPivot(handle, fs->ilu0Info_M, &numerical_zero);
918:       PetscAssert(HIPSPARSE_STATUS_ZERO_PIVOT != status, PETSC_COMM_SELF, PETSC_ERR_USER_INPUT, "Numerical zero pivot detected in csrilu02: A(%d,%d) is zero", numerical_zero, numerical_zero);
919:     }

921:     {
922:       /* hipsparseSpSV_analysis() is numeric, i.e., it requires valid matrix values, therefore, we do it after hipsparseXcsrilu02()
923:        See discussion at https://github.com/NVIDIA/CUDALibrarySamples/issues/78
924:       */
925:       PetscCallHIPSPARSE(hipsparseSpSV_analysis(handle, HIPSPARSE_OPERATION_NON_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_L, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, HIPSPARSE_SPSV_ALG_DEFAULT, fs->spsvDescr_L, fs->spsvBuffer_L));

927:       PetscCallHIPSPARSE(hipsparseSpSV_analysis(handle, HIPSPARSE_OPERATION_NON_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_U, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, HIPSPARSE_SPSV_ALG_DEFAULT, fs->spsvDescr_U, fs->spsvBuffer_U));

929:       fs->updatedSpSVAnalysis = PETSC_TRUE;
930:       /* L, U values have changed, reset the flag to indicate we need to redo hipsparseSpSV_analysis() for transpose solve */
931:       fs->updatedTransposeSpSVAnalysis = PETSC_FALSE;
932:     }

934:     fact->offloadmask            = PETSC_OFFLOAD_GPU;
935:     fact->ops->solve             = MatSolve_SeqAIJHIPSPARSE_LU; // spMatDescr_L/U uses 32-bit indices, but hipsparseSpSV_solve() supports both 32 and 64. The info is encoded in hipsparseSpMatDescr_t.
936:     fact->ops->solvetranspose    = MatSolveTranspose_SeqAIJHIPSPARSE_LU;
937:     fact->ops->matsolve          = NULL;
938:     fact->ops->matsolvetranspose = NULL;
939:     PetscCall(PetscLogGpuTimeEnd());
940:     PetscCall(PetscLogGpuFlops(fs->numericFactFlops));
941:     PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
942:   }
943:   PetscFunctionReturn(PETSC_SUCCESS);
944: }

946: static PetscErrorCode MatILUFactorSymbolic_SeqAIJHIPSPARSE_ILU0(Mat fact, Mat A, IS isrow, IS iscol, const MatFactorInfo *info)
947: {
948:   Mat_SeqAIJHIPSPARSETriFactors *fs  = (Mat_SeqAIJHIPSPARSETriFactors *)fact->spptr;
949:   Mat_SeqAIJ                    *aij = (Mat_SeqAIJ *)fact->data;
950:   PetscInt                       m, nz;
951:   PetscDeviceContext             dctx;
952:   hipStream_t                    stream;
953:   hipsparseHandle_t              handle;

955:   PetscFunctionBegin;
956:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetSparseHandles_(&dctx, &handle, &stream));
957:   {
958:     const SparsePointerModeGuard pointer_mode{handle, HIPSPARSE_POINTER_MODE_HOST};

960:     if (PetscDefined(USE_DEBUG)) {
961:       PetscBool flg, diagDense;

963:       PetscCall(PetscObjectTypeCompare((PetscObject)A, MATSEQAIJHIPSPARSE, &flg));
964:       PetscCheck(flg, PetscObjectComm((PetscObject)A), PETSC_ERR_GPU, "Expected MATSEQAIJHIPSPARSE, but input is %s", ((PetscObject)A)->type_name);
965:       PetscCheck(A->rmap->n == A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Must be square matrix, rows %" PetscInt_FMT " columns %" PetscInt_FMT, A->rmap->n, A->cmap->n);
966:       PetscCall(MatGetDiagonalMarkers_SeqAIJ(A, NULL, &diagDense));
967:       PetscCheck(diagDense, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Matrix is missing a diagonal entry");
968:     }

970:     /* Free the old stale stuff */
971:     PetscCall(MatSeqAIJHIPSPARSETriFactors_Reset(&fs));

973:     /* Copy over A's meta data to fact. Note that we also allocated fact's i,j,a on host,
974:        but they will not be used. Allocate them just for easy debugging.
975:      */
976:     PetscCall(MatDuplicateNoCreate_SeqAIJ(fact, A, MAT_DO_NOT_COPY_VALUES, PETSC_TRUE /*malloc*/));

978:     fact->offloadmask            = PETSC_OFFLOAD_BOTH;
979:     fact->factortype             = MAT_FACTOR_ILU;
980:     fact->info.factor_mallocs    = 0;
981:     fact->info.fill_ratio_given  = info->fill;
982:     fact->info.fill_ratio_needed = 1.0;

984:     aij->row = NULL;
985:     aij->col = NULL;

987:     /* ====================================================================== */
988:     /* Copy A's i, j to fact and also allocate the value array of fact.       */
989:     /* We'll do in-place factorization on fact                                */
990:     /* ====================================================================== */
991:     const PetscInt *Ai, *Aj;

993:     m  = fact->rmap->n;
994:     nz = aij->nz;

996:     PetscCallHIP(hipMalloc((void **)&fs->csrRowPtr32, sizeof(*fs->csrRowPtr32) * (m + 1)));
997:     PetscCallHIP(hipMalloc((void **)&fs->csrColIdx32, sizeof(*fs->csrColIdx32) * nz));
998:     PetscCallHIP(hipMalloc((void **)&fs->csrVal, sizeof(*fs->csrVal) * nz));
999:     PetscCall(MatSeqAIJHIPSPARSEGetIJ(A, PETSC_FALSE, &Ai, &Aj)); // Ai is uncompressed

1001:     PetscCheck(nz <= INT_MAX && m <= INT_MAX, PETSC_COMM_SELF, PETSC_ERR_SUP, "nnz %" PetscInt_FMT " and rows %" PetscInt_FMT " overflow C int", nz, m);
1002:     PetscCallThrust(thrust::transform(thrust::device.on(stream), Ai, Ai + m + 1, fs->csrRowPtr32, PetscIntToCInt()));
1003:     PetscCallThrust(thrust::transform(thrust::device.on(stream), Aj, Aj + nz, fs->csrColIdx32, PetscIntToCInt()));

1005:     /* ====================================================================== */
1006:     /* Create descriptors for M, L, U                                         */
1007:     /* ====================================================================== */
1008:     hipsparseFillMode_t fillMode;
1009:     hipsparseDiagType_t diagType;

1011:     PetscCallHIPSPARSE(hipsparseCreateMatDescr(&fs->matDescr_M));
1012:     PetscCallHIPSPARSE(hipsparseSetMatIndexBase(fs->matDescr_M, HIPSPARSE_INDEX_BASE_ZERO));
1013:     PetscCallHIPSPARSE(hipsparseSetMatType(fs->matDescr_M, HIPSPARSE_MATRIX_TYPE_GENERAL));

1015:     /* https://docs.nvidia.com/cuda/cusparse/index.html#cusparseDiagType_t
1016:       cusparseDiagType_t: This type indicates if the matrix diagonal entries are unity. The diagonal elements are always
1017:       assumed to be present, but if CUSPARSE_DIAG_TYPE_UNIT is passed to an API routine, then the routine assumes that
1018:       all diagonal entries are unity and will not read or modify those entries. Note that in this case the routine
1019:       assumes the diagonal entries are equal to one, regardless of what those entries are actually set to in memory.
1020:     */
1021:     fillMode = HIPSPARSE_FILL_MODE_LOWER;
1022:     diagType = HIPSPARSE_DIAG_TYPE_UNIT;
1023:     PetscCallHIPSPARSE(hipsparseCreateCsr(&fs->spMatDescr_L, m, m, nz, fs->csrRowPtr32, fs->csrColIdx32, fs->csrVal, HIPSPARSE_INDEX_32I, HIPSPARSE_INDEX_32I, HIPSPARSE_INDEX_BASE_ZERO, hipsparse_scalartype));
1024:     PetscCallHIPSPARSE(hipsparseSpMatSetAttribute(fs->spMatDescr_L, HIPSPARSE_SPMAT_FILL_MODE, &fillMode, sizeof(fillMode)));
1025:     PetscCallHIPSPARSE(hipsparseSpMatSetAttribute(fs->spMatDescr_L, HIPSPARSE_SPMAT_DIAG_TYPE, &diagType, sizeof(diagType)));

1027:     fillMode = HIPSPARSE_FILL_MODE_UPPER;
1028:     diagType = HIPSPARSE_DIAG_TYPE_NON_UNIT;
1029:     PetscCallHIPSPARSE(hipsparseCreateCsr(&fs->spMatDescr_U, m, m, nz, fs->csrRowPtr32, fs->csrColIdx32, fs->csrVal, HIPSPARSE_INDEX_32I, HIPSPARSE_INDEX_32I, HIPSPARSE_INDEX_BASE_ZERO, hipsparse_scalartype));
1030:     PetscCallHIPSPARSE(hipsparseSpMatSetAttribute(fs->spMatDescr_U, HIPSPARSE_SPMAT_FILL_MODE, &fillMode, sizeof(fillMode)));
1031:     PetscCallHIPSPARSE(hipsparseSpMatSetAttribute(fs->spMatDescr_U, HIPSPARSE_SPMAT_DIAG_TYPE, &diagType, sizeof(diagType)));

1033:     /* ========================================================================= */
1034:     /* Query buffer sizes for csrilu0, SpSV and allocate buffers                 */
1035:     /* ========================================================================= */
1036:     PetscCallHIPSPARSE(hipsparseCreateCsrilu02Info(&fs->ilu0Info_M));
1037:     if (m)
1038:       PetscCallHIPSPARSE(hipsparseXcsrilu02_bufferSize(handle, m, nz, /* hipsparseXcsrilu02 errors out with empty matrices (m=0) */
1039:                                                        fs->matDescr_M, fs->csrVal, fs->csrRowPtr32, fs->csrColIdx32, fs->ilu0Info_M, &fs->factBufferSize_M));

1041:     PetscCallHIP(hipMalloc((void **)&fs->X, sizeof(PetscScalar) * m));
1042:     PetscCallHIP(hipMalloc((void **)&fs->Y, sizeof(PetscScalar) * m));

1044:     PetscCallHIPSPARSE(hipsparseCreateDnVec(&fs->dnVecDescr_X, m, fs->X, hipsparse_scalartype));
1045:     PetscCallHIPSPARSE(hipsparseCreateDnVec(&fs->dnVecDescr_Y, m, fs->Y, hipsparse_scalartype));

1047:     PetscCallHIPSPARSE(hipsparseSpSV_createDescr(&fs->spsvDescr_L));
1048:     PetscCallHIPSPARSE(hipsparseSpSV_bufferSize(handle, HIPSPARSE_OPERATION_NON_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_L, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, HIPSPARSE_SPSV_ALG_DEFAULT, fs->spsvDescr_L, &fs->spsvBufferSize_L));

1050:     PetscCallHIPSPARSE(hipsparseSpSV_createDescr(&fs->spsvDescr_U));
1051:     PetscCallHIPSPARSE(hipsparseSpSV_bufferSize(handle, HIPSPARSE_OPERATION_NON_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_U, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, HIPSPARSE_SPSV_ALG_DEFAULT, fs->spsvDescr_U, &fs->spsvBufferSize_U));

1053:     /* From my experiment with the example at https://github.com/NVIDIA/CUDALibrarySamples/tree/master/cuSPARSE/bicgstab,
1054:        and discussion at https://github.com/NVIDIA/CUDALibrarySamples/issues/77,
1055:        spsvBuffer_L/U can not be shared (i.e., the same) for our case, but factBuffer_M can share with either of spsvBuffer_L/U.
1056:        To save memory, we make factBuffer_M share with the bigger of spsvBuffer_L/U.
1057:      */
1058:     if (fs->spsvBufferSize_L > fs->spsvBufferSize_U) {
1059:       PetscCallHIP(hipMalloc((void **)&fs->factBuffer_M, PetscMax(fs->spsvBufferSize_L, (size_t)fs->factBufferSize_M)));
1060:       fs->spsvBuffer_L = fs->factBuffer_M;
1061:       PetscCallHIP(hipMalloc((void **)&fs->spsvBuffer_U, fs->spsvBufferSize_U));
1062:     } else {
1063:       PetscCallHIP(hipMalloc((void **)&fs->factBuffer_M, PetscMax(fs->spsvBufferSize_U, (size_t)fs->factBufferSize_M)));
1064:       fs->spsvBuffer_U = fs->factBuffer_M;
1065:       PetscCallHIP(hipMalloc((void **)&fs->spsvBuffer_L, fs->spsvBufferSize_L));
1066:     }

1068:     /* ========================================================================== */
1069:     /* Perform analysis of ilu0 on M, SpSv on L and U                             */
1070:     /* The lower(upper) triangular part of M has the same sparsity pattern as L(U)*/
1071:     /* ========================================================================== */
1072:     int               structural_zero;
1073:     hipsparseStatus_t status;

1075:     fs->policy_M = HIPSPARSE_SOLVE_POLICY_USE_LEVEL;
1076:     if (m)
1077:       PetscCallHIPSPARSE(hipsparseXcsrilu02_analysis(handle, m, nz, /* hipsparseXcsrilu02 errors out with empty matrices (m=0) */
1078:                                                      fs->matDescr_M, fs->csrVal, fs->csrRowPtr32, fs->csrColIdx32, fs->ilu0Info_M, fs->policy_M, fs->factBuffer_M));
1079:     if (PetscDefined(USE_DEBUG)) {
1080:       /* hipsparseXcsrilu02_zeroPivot() is a blocking call. It calls hipDeviceSynchronize() to make sure all previous kernels are done. */
1081:       status = hipsparseXcsrilu02_zeroPivot(handle, fs->ilu0Info_M, &structural_zero);
1082:       PetscCheck(HIPSPARSE_STATUS_ZERO_PIVOT != status, PETSC_COMM_SELF, PETSC_ERR_USER_INPUT, "Structural zero pivot detected in csrilu02: A(%d,%d) is missing", structural_zero, structural_zero);
1083:     }

1085:     /* Estimate FLOPs of the numeric factorization */
1086:     {
1087:       Mat_SeqAIJ     *Aseq = (Mat_SeqAIJ *)A->data;
1088:       PetscInt       *Ai, nzRow, nzLeft;
1089:       const PetscInt *adiag;
1090:       PetscLogDouble  flops = 0.0;

1092:       PetscCall(MatGetDiagonalMarkers_SeqAIJ(A, &adiag, NULL));
1093:       Ai = Aseq->i;
1094:       for (PetscInt i = 0; i < m; i++) {
1095:         if (Ai[i] < adiag[i] && adiag[i] < Ai[i + 1]) { /* There are nonzeros left to the diagonal of row i */
1096:           nzRow  = Ai[i + 1] - Ai[i];
1097:           nzLeft = adiag[i] - Ai[i];
1098:           /* We want to eliminate nonzeros left to the diagonal one by one. Assume each time, nonzeros right
1099:             and include the eliminated one will be updated, which incurs a multiplication and an addition.
1100:           */
1101:           nzLeft = (nzRow - 1) / 2;
1102:           flops += nzLeft * (2.0 * nzRow - nzLeft + 1);
1103:         }
1104:       }
1105:       fs->numericFactFlops = flops;
1106:     }
1107:     fact->ops->lufactornumeric = MatILUFactorNumeric_SeqAIJHIPSPARSE_ILU0;
1108:     PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
1109:   }
1110:   PetscFunctionReturn(PETSC_SUCCESS);
1111: }

1113: static PetscErrorCode MatSolve_SeqAIJHIPSPARSE_ICC0(Mat fact, Vec b, Vec x)
1114: {
1115:   Mat_SeqAIJHIPSPARSETriFactors *fs  = (Mat_SeqAIJHIPSPARSETriFactors *)fact->spptr;
1116:   Mat_SeqAIJ                    *aij = (Mat_SeqAIJ *)fact->data;
1117:   const PetscScalar             *barray;
1118:   PetscScalar                   *xarray;
1119:   PetscDeviceContext             dctx;
1120:   hipsparseHandle_t              handle;

1122:   PetscFunctionBegin;
1123:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetSparseHandles_(&dctx, &handle));
1124:   {
1125:     const SparsePointerModeGuard pointer_mode{handle, HIPSPARSE_POINTER_MODE_HOST};

1127:     PetscCall(VecHIPGetArrayWrite(x, &xarray));
1128:     PetscCall(VecHIPGetArrayRead(b, &barray));
1129:     PetscCall(PetscLogGpuTimeBegin());

1131:     /* Solve L*y = b */
1132:     PetscCallHIPSPARSE(hipsparseDnVecSetValues(fs->dnVecDescr_X, (void *)barray));
1133:     PetscCallHIPSPARSE(hipsparseDnVecSetValues(fs->dnVecDescr_Y, fs->Y));
1134: #if PETSC_PKG_HIP_VERSION_EQ(5, 6, 0) || PETSC_PKG_HIP_VERSION_GE(6, 0, 0)
1135:     PetscCallHIPSPARSE(hipsparseSpSV_solve(handle, HIPSPARSE_OPERATION_NON_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_L, /* L Y = X */
1136:                                            fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, HIPSPARSE_SPSV_ALG_DEFAULT, fs->spsvDescr_L));
1137: #else
1138:     PetscCallHIPSPARSE(hipsparseSpSV_solve(handle, HIPSPARSE_OPERATION_NON_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_L, /* L Y = X */
1139:                                            fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, HIPSPARSE_SPSV_ALG_DEFAULT, fs->spsvDescr_L, fs->spsvBuffer_L));
1140: #endif
1141:     /* Solve Lt*x = y */
1142:     PetscCallHIPSPARSE(hipsparseDnVecSetValues(fs->dnVecDescr_X, xarray));
1143: #if PETSC_PKG_HIP_VERSION_EQ(5, 6, 0) || PETSC_PKG_HIP_VERSION_GE(6, 0, 0)
1144:     PetscCallHIPSPARSE(hipsparseSpSV_solve(handle, HIPSPARSE_OPERATION_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_Lt, /* Lt X = Y */
1145:                                            fs->dnVecDescr_Y, fs->dnVecDescr_X, hipsparse_scalartype, HIPSPARSE_SPSV_ALG_DEFAULT, fs->spsvDescr_Lt));
1146: #else
1147:     PetscCallHIPSPARSE(hipsparseSpSV_solve(handle, HIPSPARSE_OPERATION_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_Lt, /* Lt X = Y */
1148:                                            fs->dnVecDescr_Y, fs->dnVecDescr_X, hipsparse_scalartype, HIPSPARSE_SPSV_ALG_DEFAULT, fs->spsvDescr_Lt, fs->spsvBuffer_Lt));
1149: #endif
1150:     PetscCall(VecHIPRestoreArrayRead(b, &barray));
1151:     PetscCall(VecHIPRestoreArrayWrite(x, &xarray));

1153:     PetscCall(PetscLogGpuTimeEnd());
1154:     PetscCall(PetscLogGpuFlops(2.0 * aij->nz - fact->rmap->n));
1155:     PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
1156:   }
1157:   PetscFunctionReturn(PETSC_SUCCESS);
1158: }

1160: static PetscErrorCode MatICCFactorNumeric_SeqAIJHIPSPARSE_ICC0(Mat fact, Mat A, const MatFactorInfo *info)
1161: {
1162:   Mat_SeqAIJHIPSPARSETriFactors *fs    = (Mat_SeqAIJHIPSPARSETriFactors *)fact->spptr;
1163:   Mat_SeqAIJ                    *aij   = (Mat_SeqAIJ *)fact->data;
1164:   Mat_SeqAIJHIPSPARSE           *Acusp = (Mat_SeqAIJHIPSPARSE *)A->spptr;
1165:   CsrMatrix                     *Acsr;
1166:   PetscInt                       m, nz;
1167:   PetscBool                      flg;
1168:   PetscDeviceContext             dctx;
1169:   hipStream_t                    stream;
1170:   hipsparseHandle_t              handle;

1172:   PetscFunctionBegin;
1173:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetSparseHandles_(&dctx, &handle, &stream));
1174:   {
1175:     const SparsePointerModeGuard pointer_mode{handle, HIPSPARSE_POINTER_MODE_HOST};

1177:     if (PetscDefined(USE_DEBUG)) {
1178:       PetscCall(PetscObjectTypeCompare((PetscObject)A, MATSEQAIJHIPSPARSE, &flg));
1179:       PetscCheck(flg, PetscObjectComm((PetscObject)A), PETSC_ERR_GPU, "Expected MATSEQAIJHIPSPARSE, but input is %s", ((PetscObject)A)->type_name);
1180:     }

1182:     /* Copy A's value to fact */
1183:     m  = fact->rmap->n;
1184:     nz = aij->nz;
1185:     PetscCall(MatSeqAIJHIPSPARSECopyToGPU(A));
1186:     Acsr = (CsrMatrix *)Acusp->mat->mat;
1187:     PetscCallHIP(hipMemcpyAsync(fs->csrVal, Acsr->values->data().get(), sizeof(PetscScalar) * nz, hipMemcpyDeviceToDevice, stream));

1189:     /* Factorize fact inplace */
1190:     /* https://docs.nvidia.com/cuda/cusparse/index.html#csric02_solve
1191:        csric02() only takes the lower triangular part of matrix A to perform factorization.
1192:        The matrix type must be CUSPARSE_MATRIX_TYPE_GENERAL, the fill mode and diagonal type are ignored,
1193:        and the strictly upper triangular part is ignored and never touched. It does not matter if A is Hermitian or not.
1194:        In other words, from the point of view of csric02() A is Hermitian and only the lower triangular part is provided.
1195:      */
1196:     if (m) PetscCallHIPSPARSE(hipsparseXcsric02(handle, m, nz, fs->matDescr_M, fs->csrVal, fs->csrRowPtr32, fs->csrColIdx32, fs->ic0Info_M, fs->policy_M, fs->factBuffer_M));
1197:     if (PetscDefined(USE_DEBUG)) {
1198:       int               numerical_zero;
1199:       hipsparseStatus_t status;
1200:       status = hipsparseXcsric02_zeroPivot(handle, fs->ic0Info_M, &numerical_zero);
1201:       PetscAssert(HIPSPARSE_STATUS_ZERO_PIVOT != status, PETSC_COMM_SELF, PETSC_ERR_USER_INPUT, "Numerical zero pivot detected in csric02: A(%d,%d) is zero", numerical_zero, numerical_zero);
1202:     }

1204:     {
1205:       PetscCallHIPSPARSE(hipsparseSpSV_analysis(handle, HIPSPARSE_OPERATION_NON_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_L, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, HIPSPARSE_SPSV_ALG_DEFAULT, fs->spsvDescr_L, fs->spsvBuffer_L));

1207:       /* Note that cusparse reports this error if we use double and CUSPARSE_OPERATION_CONJUGATE_TRANSPOSE
1208:       ** On entry to cusparseSpSV_analysis(): conjugate transpose (opA) is not supported for matA data type, current -> CUDA_R_64F
1209:     */
1210:       PetscCallHIPSPARSE(hipsparseSpSV_analysis(handle, HIPSPARSE_OPERATION_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_Lt, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, HIPSPARSE_SPSV_ALG_DEFAULT, fs->spsvDescr_Lt, fs->spsvBuffer_Lt));
1211:       fs->updatedSpSVAnalysis = PETSC_TRUE;
1212:     }

1214:     fact->offloadmask            = PETSC_OFFLOAD_GPU;
1215:     fact->ops->solve             = MatSolve_SeqAIJHIPSPARSE_ICC0;
1216:     fact->ops->solvetranspose    = MatSolve_SeqAIJHIPSPARSE_ICC0;
1217:     fact->ops->matsolve          = NULL;
1218:     fact->ops->matsolvetranspose = NULL;
1219:     PetscCall(PetscLogGpuFlops(fs->numericFactFlops));
1220:     PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
1221:   }
1222:   PetscFunctionReturn(PETSC_SUCCESS);
1223: }

1225: static PetscErrorCode MatICCFactorSymbolic_SeqAIJHIPSPARSE_ICC0(Mat fact, Mat A, IS perm, const MatFactorInfo *info)
1226: {
1227:   Mat_SeqAIJHIPSPARSETriFactors *fs  = (Mat_SeqAIJHIPSPARSETriFactors *)fact->spptr;
1228:   Mat_SeqAIJ                    *aij = (Mat_SeqAIJ *)fact->data;
1229:   PetscInt                       m, nz;
1230:   PetscDeviceContext             dctx;
1231:   hipStream_t                    stream;
1232:   hipsparseHandle_t              handle;

1234:   PetscFunctionBegin;
1235:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetSparseHandles_(&dctx, &handle, &stream));
1236:   {
1237:     const SparsePointerModeGuard pointer_mode{handle, HIPSPARSE_POINTER_MODE_HOST};

1239:     if (PetscDefined(USE_DEBUG)) {
1240:       PetscBool flg, diagDense;

1242:       PetscCall(PetscObjectTypeCompare((PetscObject)A, MATSEQAIJHIPSPARSE, &flg));
1243:       PetscCheck(flg, PetscObjectComm((PetscObject)A), PETSC_ERR_GPU, "Expected MATSEQAIJHIPSPARSE, but input is %s", ((PetscObject)A)->type_name);
1244:       PetscCheck(A->rmap->n == A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Must be square matrix, rows %" PetscInt_FMT " columns %" PetscInt_FMT, A->rmap->n, A->cmap->n);
1245:       PetscCall(MatGetDiagonalMarkers_SeqAIJ(A, NULL, &diagDense));
1246:       PetscCheck(diagDense, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Matrix is missing diagonal entries");
1247:     }

1249:     /* Free the old stale stuff */
1250:     PetscCall(MatSeqAIJHIPSPARSETriFactors_Reset(&fs));

1252:     /* Copy over A's meta data to fact. Note that we also allocated fact's i,j,a on host,
1253:        but they will not be used. Allocate them just for easy debugging.
1254:      */
1255:     PetscCall(MatDuplicateNoCreate_SeqAIJ(fact, A, MAT_DO_NOT_COPY_VALUES, PETSC_TRUE /*malloc*/));

1257:     fact->offloadmask            = PETSC_OFFLOAD_BOTH;
1258:     fact->factortype             = MAT_FACTOR_ICC;
1259:     fact->info.factor_mallocs    = 0;
1260:     fact->info.fill_ratio_given  = info->fill;
1261:     fact->info.fill_ratio_needed = 1.0;

1263:     aij->row = NULL;
1264:     aij->col = NULL;

1266:     /* ====================================================================== */
1267:     /* Copy A's i, j to fact and also allocate the value array of fact.       */
1268:     /* We'll do in-place factorization on fact                                */
1269:     /* ====================================================================== */
1270:     const PetscInt *Ai, *Aj;

1272:     m  = fact->rmap->n;
1273:     nz = aij->nz;

1275:     PetscCallHIP(hipMalloc((void **)&fs->csrRowPtr32, sizeof(*fs->csrRowPtr32) * (m + 1)));
1276:     PetscCallHIP(hipMalloc((void **)&fs->csrColIdx32, sizeof(*fs->csrColIdx32) * nz));
1277:     PetscCallHIP(hipMalloc((void **)&fs->csrVal, sizeof(PetscScalar) * nz));
1278:     PetscCall(MatSeqAIJHIPSPARSEGetIJ(A, PETSC_FALSE, &Ai, &Aj)); // Ai is uncompressed

1280:     PetscCheck(nz <= INT_MAX && m <= INT_MAX, PETSC_COMM_SELF, PETSC_ERR_SUP, "nnz %" PetscInt_FMT " and rows %" PetscInt_FMT " overflow C int", nz, m);
1281:     PetscCallThrust(thrust::transform(thrust::device.on(stream), Ai, Ai + m + 1, fs->csrRowPtr32, PetscIntToCInt()));
1282:     PetscCallThrust(thrust::transform(thrust::device.on(stream), Aj, Aj + nz, fs->csrColIdx32, PetscIntToCInt()));

1284:     /* ====================================================================== */
1285:     /* Create mat descriptors for M, L                                        */
1286:     /* ====================================================================== */
1287:     hipsparseFillMode_t fillMode;
1288:     hipsparseDiagType_t diagType;

1290:     PetscCallHIPSPARSE(hipsparseCreateMatDescr(&fs->matDescr_M));
1291:     PetscCallHIPSPARSE(hipsparseSetMatIndexBase(fs->matDescr_M, HIPSPARSE_INDEX_BASE_ZERO));
1292:     PetscCallHIPSPARSE(hipsparseSetMatType(fs->matDescr_M, HIPSPARSE_MATRIX_TYPE_GENERAL));

1294:     /* https://docs.nvidia.com/cuda/cusparse/index.html#cusparseDiagType_t
1295:       cusparseDiagType_t: This type indicates if the matrix diagonal entries are unity. The diagonal elements are always
1296:       assumed to be present, but if CUSPARSE_DIAG_TYPE_UNIT is passed to an API routine, then the routine assumes that
1297:       all diagonal entries are unity and will not read or modify those entries. Note that in this case the routine
1298:       assumes the diagonal entries are equal to one, regardless of what those entries are actually set to in memory.
1299:     */
1300:     fillMode = HIPSPARSE_FILL_MODE_LOWER;
1301:     diagType = HIPSPARSE_DIAG_TYPE_NON_UNIT;
1302:     PetscCallHIPSPARSE(hipsparseCreateCsr(&fs->spMatDescr_L, m, m, nz, fs->csrRowPtr32, fs->csrColIdx32, fs->csrVal, HIPSPARSE_INDEX_32I, HIPSPARSE_INDEX_32I, HIPSPARSE_INDEX_BASE_ZERO, hipsparse_scalartype));
1303:     PetscCallHIPSPARSE(hipsparseSpMatSetAttribute(fs->spMatDescr_L, HIPSPARSE_SPMAT_FILL_MODE, &fillMode, sizeof(fillMode)));
1304:     PetscCallHIPSPARSE(hipsparseSpMatSetAttribute(fs->spMatDescr_L, HIPSPARSE_SPMAT_DIAG_TYPE, &diagType, sizeof(diagType)));

1306:     /* ========================================================================= */
1307:     /* Query buffer sizes for csric0, SpSV of L and Lt, and allocate buffers     */
1308:     /* ========================================================================= */
1309:     PetscCallHIPSPARSE(hipsparseCreateCsric02Info(&fs->ic0Info_M));
1310:     if (m) PetscCallHIPSPARSE(hipsparseXcsric02_bufferSize(handle, m, nz, fs->matDescr_M, fs->csrVal, fs->csrRowPtr32, fs->csrColIdx32, fs->ic0Info_M, &fs->factBufferSize_M));

1312:     PetscCallHIP(hipMalloc((void **)&fs->X, sizeof(PetscScalar) * m));
1313:     PetscCallHIP(hipMalloc((void **)&fs->Y, sizeof(PetscScalar) * m));

1315:     PetscCallHIPSPARSE(hipsparseCreateDnVec(&fs->dnVecDescr_X, m, fs->X, hipsparse_scalartype));
1316:     PetscCallHIPSPARSE(hipsparseCreateDnVec(&fs->dnVecDescr_Y, m, fs->Y, hipsparse_scalartype));

1318:     PetscCallHIPSPARSE(hipsparseSpSV_createDescr(&fs->spsvDescr_L));
1319:     PetscCallHIPSPARSE(hipsparseSpSV_bufferSize(handle, HIPSPARSE_OPERATION_NON_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_L, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, HIPSPARSE_SPSV_ALG_DEFAULT, fs->spsvDescr_L, &fs->spsvBufferSize_L));

1321:     PetscCall(MatSeqAIJHIPSPARSECreateTransposeSolveMat(fs->spMatDescr_L, &fs->spMatDescr_Lt));
1322:     PetscCallHIPSPARSE(hipsparseSpSV_createDescr(&fs->spsvDescr_Lt));
1323:     PetscCallHIPSPARSE(hipsparseSpSV_bufferSize(handle, HIPSPARSE_OPERATION_TRANSPOSE, &PETSC_HIPSPARSE_ONE, fs->spMatDescr_Lt, fs->dnVecDescr_X, fs->dnVecDescr_Y, hipsparse_scalartype, HIPSPARSE_SPSV_ALG_DEFAULT, fs->spsvDescr_Lt, &fs->spsvBufferSize_Lt));

1325:     /* To save device memory, we make the factorization buffer share with one of the solver buffer.
1326:        See also comments in MatILUFactorSymbolic_SeqAIJCUSPARSE_ILU0().
1327:      */
1328:     if (fs->spsvBufferSize_L > fs->spsvBufferSize_Lt) {
1329:       PetscCallHIP(hipMalloc((void **)&fs->factBuffer_M, PetscMax(fs->spsvBufferSize_L, (size_t)fs->factBufferSize_M)));
1330:       fs->spsvBuffer_L = fs->factBuffer_M;
1331:       PetscCallHIP(hipMalloc((void **)&fs->spsvBuffer_Lt, fs->spsvBufferSize_Lt));
1332:     } else {
1333:       PetscCallHIP(hipMalloc((void **)&fs->factBuffer_M, PetscMax(fs->spsvBufferSize_Lt, (size_t)fs->factBufferSize_M)));
1334:       fs->spsvBuffer_Lt = fs->factBuffer_M;
1335:       PetscCallHIP(hipMalloc((void **)&fs->spsvBuffer_L, fs->spsvBufferSize_L));
1336:     }

1338:     /* ========================================================================== */
1339:     /* Perform analysis of ic0 on M                                               */
1340:     /* The lower triangular part of M has the same sparsity pattern as L          */
1341:     /* ========================================================================== */
1342:     int               structural_zero;
1343:     hipsparseStatus_t status;

1345:     fs->policy_M = HIPSPARSE_SOLVE_POLICY_USE_LEVEL;
1346:     if (m) PetscCallHIPSPARSE(hipsparseXcsric02_analysis(handle, m, nz, fs->matDescr_M, fs->csrVal, fs->csrRowPtr32, fs->csrColIdx32, fs->ic0Info_M, fs->policy_M, fs->factBuffer_M));
1347:     if (PetscDefined(USE_DEBUG)) {
1348:       /* hipsparseXcsric02_zeroPivot() is a blocking call. It calls cudaDeviceSynchronize() to make sure all previous kernels are done. */
1349:       status = hipsparseXcsric02_zeroPivot(handle, fs->ic0Info_M, &structural_zero);
1350:       PetscCheck(HIPSPARSE_STATUS_ZERO_PIVOT != status, PETSC_COMM_SELF, PETSC_ERR_USER_INPUT, "Structural zero pivot detected in csric02: A(%d,%d) is missing", structural_zero, structural_zero);
1351:     }

1353:     /* Estimate FLOPs of the numeric factorization */
1354:     {
1355:       Mat_SeqAIJ    *Aseq = (Mat_SeqAIJ *)A->data;
1356:       PetscInt      *Ai, nzRow, nzLeft;
1357:       PetscLogDouble flops = 0.0;

1359:       Ai = Aseq->i;
1360:       for (PetscInt i = 0; i < m; i++) {
1361:         nzRow = Ai[i + 1] - Ai[i];
1362:         if (nzRow > 1) {
1363:           /* We want to eliminate nonzeros left to the diagonal one by one. Assume each time, nonzeros right
1364:             and include the eliminated one will be updated, which incurs a multiplication and an addition.
1365:           */
1366:           nzLeft = (nzRow - 1) / 2;
1367:           flops += nzLeft * (2.0 * nzRow - nzLeft + 1);
1368:         }
1369:       }
1370:       fs->numericFactFlops = flops;
1371:     }
1372:     fact->ops->choleskyfactornumeric = MatICCFactorNumeric_SeqAIJHIPSPARSE_ICC0;
1373:     PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
1374:   }
1375:   PetscFunctionReturn(PETSC_SUCCESS);
1376: }

1378: static PetscErrorCode MatLUFactorNumeric_SeqAIJHIPSPARSE(Mat B, Mat A, const MatFactorInfo *info)
1379: {
1380:   // use_cpu_solve is a field in Mat_SeqAIJHIPSPARSE. B, a factored matrix, uses Mat_SeqAIJHIPSPARSETriFactors.
1381:   Mat_SeqAIJHIPSPARSE *hipsparsestruct = static_cast<Mat_SeqAIJHIPSPARSE *>(A->spptr);

1383:   PetscFunctionBegin;
1384:   PetscCall(MatSeqAIJHIPSPARSECopyFromGPU(A));
1385:   PetscCall(MatLUFactorNumeric_SeqAIJ(B, A, info));
1386:   B->offloadmask = PETSC_OFFLOAD_CPU;

1388:   if (!hipsparsestruct->use_cpu_solve) {
1389:     B->ops->solve          = MatSolve_SeqAIJHIPSPARSE_LU;
1390:     B->ops->solvetranspose = MatSolveTranspose_SeqAIJHIPSPARSE_LU;
1391:   }
1392:   B->ops->matsolve          = NULL;
1393:   B->ops->matsolvetranspose = NULL;

1395:   /* get the triangular factors */
1396:   if (!hipsparsestruct->use_cpu_solve) PetscCall(MatSeqAIJHIPSPARSEILUAnalysisAndCopyToGPU(B));
1397:   PetscFunctionReturn(PETSC_SUCCESS);
1398: }

1400: static PetscErrorCode MatLUFactorSymbolic_SeqAIJHIPSPARSE(Mat B, Mat A, IS isrow, IS iscol, const MatFactorInfo *info)
1401: {
1402:   Mat_SeqAIJHIPSPARSETriFactors *hipsparseTriFactors = (Mat_SeqAIJHIPSPARSETriFactors *)B->spptr;

1404:   PetscFunctionBegin;
1405:   PetscCall(MatSeqAIJHIPSPARSETriFactors_Reset(&hipsparseTriFactors));
1406:   PetscCall(MatLUFactorSymbolic_SeqAIJ(B, A, isrow, iscol, info));
1407:   B->ops->lufactornumeric = MatLUFactorNumeric_SeqAIJHIPSPARSE;
1408:   PetscFunctionReturn(PETSC_SUCCESS);
1409: }

1411: static PetscErrorCode MatILUFactorSymbolic_SeqAIJHIPSPARSE(Mat B, Mat A, IS isrow, IS iscol, const MatFactorInfo *info)
1412: {
1413:   Mat_SeqAIJHIPSPARSETriFactors *hipsparseTriFactors = (Mat_SeqAIJHIPSPARSETriFactors *)B->spptr;

1415:   PetscFunctionBegin;
1416:   PetscBool row_identity = PETSC_FALSE, col_identity = PETSC_FALSE;
1417:   if (!info->factoronhost) {
1418:     PetscCall(ISIdentity(isrow, &row_identity));
1419:     PetscCall(ISIdentity(iscol, &col_identity));
1420:   }
1421:   if (!info->levels && row_identity && col_identity) PetscCall(MatILUFactorSymbolic_SeqAIJHIPSPARSE_ILU0(B, A, isrow, iscol, info));
1422:   else {
1423:     PetscCall(MatSeqAIJHIPSPARSETriFactors_Reset(&hipsparseTriFactors));
1424:     PetscCall(MatILUFactorSymbolic_SeqAIJ(B, A, isrow, iscol, info));
1425:     B->ops->lufactornumeric = MatLUFactorNumeric_SeqAIJHIPSPARSE;
1426:   }
1427:   PetscFunctionReturn(PETSC_SUCCESS);
1428: }

1430: static PetscErrorCode MatICCFactorSymbolic_SeqAIJHIPSPARSE(Mat B, Mat A, IS perm, const MatFactorInfo *info)
1431: {
1432:   Mat_SeqAIJHIPSPARSETriFactors *hipsparseTriFactors = (Mat_SeqAIJHIPSPARSETriFactors *)B->spptr;

1434:   PetscFunctionBegin;
1435:   PetscBool perm_identity = PETSC_FALSE;
1436:   if (!info->factoronhost) PetscCall(ISIdentity(perm, &perm_identity));
1437:   if (!info->levels && perm_identity) PetscCall(MatICCFactorSymbolic_SeqAIJHIPSPARSE_ICC0(B, A, perm, info));
1438:   else {
1439:     PetscCall(MatSeqAIJHIPSPARSETriFactors_Reset(&hipsparseTriFactors));
1440:     PetscCall(MatICCFactorSymbolic_SeqAIJ(B, A, perm, info));
1441:     B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqAIJHIPSPARSE;
1442:   }
1443:   PetscFunctionReturn(PETSC_SUCCESS);
1444: }

1446: static PetscErrorCode MatCholeskyFactorSymbolic_SeqAIJHIPSPARSE(Mat B, Mat A, IS perm, const MatFactorInfo *info)
1447: {
1448:   Mat_SeqAIJHIPSPARSETriFactors *hipsparseTriFactors = (Mat_SeqAIJHIPSPARSETriFactors *)B->spptr;

1450:   PetscFunctionBegin;
1451:   PetscCall(MatSeqAIJHIPSPARSETriFactors_Reset(&hipsparseTriFactors));
1452:   PetscCall(MatCholeskyFactorSymbolic_SeqAIJ(B, A, perm, info));
1453:   B->ops->choleskyfactornumeric = MatCholeskyFactorNumeric_SeqAIJHIPSPARSE;
1454:   PetscFunctionReturn(PETSC_SUCCESS);
1455: }

1457: static PetscErrorCode MatFactorGetSolverType_seqaij_hipsparse(Mat A, MatSolverType *type)
1458: {
1459:   PetscFunctionBegin;
1460:   *type = MATSOLVERHIPSPARSE;
1461:   PetscFunctionReturn(PETSC_SUCCESS);
1462: }

1464: /*MC
1465:   MATSOLVERHIPSPARSE = "hipsparse" - A matrix type providing triangular solvers for sequential matrices
1466:   on a single GPU of type, `MATSEQAIJHIPSPARSE`. Currently supported
1467:   algorithms are ILU(k) and ICC(k). Typically, deeper factorizations (larger k) results in poorer
1468:   performance in the triangular solves. Full LU, and Cholesky decompositions can be solved through the
1469:   HipSPARSE triangular solve algorithm. However, the performance can be quite poor and thus these
1470:   algorithms are not recommended. This class does NOT support direct solver operations.

1472:   Level: beginner

1474: .seealso: [](ch_matrices), `Mat`, `MATSEQAIJHIPSPARSE`, `PCFactorSetMatSolverType()`, `MatSolverType`, `MatCreateSeqAIJHIPSPARSE()`, `MATAIJHIPSPARSE`, `MatCreateAIJHIPSPARSE()`, `MatHIPSPARSESetFormat()`, `MatHIPSPARSEStorageFormat`, `MatHIPSPARSEFormatOperation`
1475: M*/

1477: PETSC_EXTERN PetscErrorCode MatGetFactor_seqaijhipsparse_hipsparse(Mat A, MatFactorType ftype, Mat *B)
1478: {
1479:   PetscInt n = A->rmap->n;

1481:   PetscFunctionBegin;
1482:   PetscCall(MatCreate(PetscObjectComm((PetscObject)A), B));
1483:   PetscCall(MatSetSizes(*B, n, n, n, n));
1484:   (*B)->factortype = ftype; // factortype makes MatSetType() allocate spptr of type Mat_SeqAIJHIPSPARSETriFactors
1485:   PetscCall(MatSetType(*B, MATSEQAIJHIPSPARSE));

1487:   if (A->boundtocpu && A->bindingpropagates) PetscCall(MatBindToCPU(*B, PETSC_TRUE));
1488:   if (ftype == MAT_FACTOR_LU || ftype == MAT_FACTOR_ILU || ftype == MAT_FACTOR_ILUDT) {
1489:     PetscCall(MatSetBlockSizesFromMats(*B, A, A));
1490:     if (!A->boundtocpu) {
1491:       (*B)->ops->ilufactorsymbolic = MatILUFactorSymbolic_SeqAIJHIPSPARSE;
1492:       (*B)->ops->lufactorsymbolic  = MatLUFactorSymbolic_SeqAIJHIPSPARSE;
1493:     } else {
1494:       (*B)->ops->ilufactorsymbolic = MatILUFactorSymbolic_SeqAIJ;
1495:       (*B)->ops->lufactorsymbolic  = MatLUFactorSymbolic_SeqAIJ;
1496:     }
1497:     PetscCall(PetscStrallocpy(MATORDERINGND, (char **)&(*B)->preferredordering[MAT_FACTOR_LU]));
1498:     PetscCall(PetscStrallocpy(MATORDERINGNATURAL, (char **)&(*B)->preferredordering[MAT_FACTOR_ILU]));
1499:     PetscCall(PetscStrallocpy(MATORDERINGNATURAL, (char **)&(*B)->preferredordering[MAT_FACTOR_ILUDT]));
1500:   } else if (ftype == MAT_FACTOR_CHOLESKY || ftype == MAT_FACTOR_ICC) {
1501:     if (!A->boundtocpu) {
1502:       (*B)->ops->iccfactorsymbolic      = MatICCFactorSymbolic_SeqAIJHIPSPARSE;
1503:       (*B)->ops->choleskyfactorsymbolic = MatCholeskyFactorSymbolic_SeqAIJHIPSPARSE;
1504:     } else {
1505:       (*B)->ops->iccfactorsymbolic      = MatICCFactorSymbolic_SeqAIJ;
1506:       (*B)->ops->choleskyfactorsymbolic = MatCholeskyFactorSymbolic_SeqAIJ;
1507:     }
1508:     PetscCall(PetscStrallocpy(MATORDERINGND, (char **)&(*B)->preferredordering[MAT_FACTOR_CHOLESKY]));
1509:     PetscCall(PetscStrallocpy(MATORDERINGNATURAL, (char **)&(*B)->preferredordering[MAT_FACTOR_ICC]));
1510:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Factor type not supported for HIPSPARSE Matrix Types");

1512:   PetscCall(MatSeqAIJSetPreallocation(*B, MAT_SKIP_ALLOCATION, NULL));
1513:   (*B)->canuseordering = PETSC_TRUE;
1514:   PetscCall(PetscObjectComposeFunction((PetscObject)*B, "MatFactorGetSolverType_C", MatFactorGetSolverType_seqaij_hipsparse));
1515:   PetscFunctionReturn(PETSC_SUCCESS);
1516: }

1518: static PetscErrorCode MatSeqAIJHIPSPARSECopyFromGPU(Mat A)
1519: {
1520:   Mat_SeqAIJ                    *a    = (Mat_SeqAIJ *)A->data;
1521:   Mat_SeqAIJHIPSPARSE           *cusp = (Mat_SeqAIJHIPSPARSE *)A->spptr;
1522:   Mat_SeqAIJHIPSPARSETriFactors *fs   = (Mat_SeqAIJHIPSPARSETriFactors *)A->spptr;
1523:   PetscDeviceContext             dctx;
1524:   hipStream_t                    stream;

1526:   PetscFunctionBegin;
1527:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetHandles_(&dctx, &stream));
1528:   if (A->offloadmask == PETSC_OFFLOAD_GPU) {
1529:     PetscCall(PetscLogEventBegin(MAT_HIPSPARSECopyFromGPU, A, 0, 0, 0));
1530:     if (A->factortype == MAT_FACTOR_NONE) {
1531:       CsrMatrix *matrix = (CsrMatrix *)cusp->mat->mat;
1532:       PetscCallHIP(hipMemcpyAsync(a->a, matrix->values->data().get(), a->nz * sizeof(PetscScalar), hipMemcpyDeviceToHost, stream));
1533:     } else if (fs->csrVal) {
1534:       /* We have a factorized matrix on device and are able to copy it to host */
1535:       PetscCallHIP(hipMemcpyAsync(a->a, fs->csrVal, a->nz * sizeof(PetscScalar), hipMemcpyDeviceToHost, stream));
1536:     } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "No support for copying this type of factorized matrix from device to host");
1537:     PetscCall(PetscDeviceContextSynchronize(dctx));
1538:     PetscCall(PetscLogGpuToCpu(a->nz * sizeof(PetscScalar)));
1539:     PetscCall(PetscLogEventEnd(MAT_HIPSPARSECopyFromGPU, A, 0, 0, 0));
1540:     A->offloadmask = PETSC_OFFLOAD_BOTH;
1541:   }
1542:   PetscFunctionReturn(PETSC_SUCCESS);
1543: }

1545: static PetscErrorCode MatSeqAIJGetArray_SeqAIJHIPSPARSE(Mat A, PetscScalar *array[])
1546: {
1547:   return MatSeqAIJHIPSPARSE_CUPM_t::SeqAIJGetArray(A, array);
1548: }

1550: static PetscErrorCode MatSeqAIJRestoreArray_SeqAIJHIPSPARSE(Mat A, PetscScalar *array[])
1551: {
1552:   return MatSeqAIJHIPSPARSE_CUPM_t::SeqAIJRestoreArray(A, array);
1553: }

1555: static PetscErrorCode MatSeqAIJGetArrayRead_SeqAIJHIPSPARSE(Mat A, const PetscScalar *array[])
1556: {
1557:   return MatSeqAIJHIPSPARSE_CUPM_t::SeqAIJGetArrayRead(A, array);
1558: }

1560: static PetscErrorCode MatSeqAIJRestoreArrayRead_SeqAIJHIPSPARSE(Mat A, const PetscScalar *array[])
1561: {
1562:   return MatSeqAIJHIPSPARSE_CUPM_t::SeqAIJRestoreArrayRead(A, array);
1563: }

1565: static PetscErrorCode MatSeqAIJGetArrayWrite_SeqAIJHIPSPARSE(Mat A, PetscScalar *array[])
1566: {
1567:   return MatSeqAIJHIPSPARSE_CUPM_t::SeqAIJGetArrayWrite(A, array);
1568: }

1570: static PetscErrorCode MatSeqAIJRestoreArrayWrite_SeqAIJHIPSPARSE(Mat A, PetscScalar *array[])
1571: {
1572:   return MatSeqAIJHIPSPARSE_CUPM_t::SeqAIJRestoreArrayWrite(A, array);
1573: }

1575: static PetscErrorCode MatSeqAIJGetCSRAndMemType_SeqAIJHIPSPARSE(Mat A, const PetscInt **i, const PetscInt **j, PetscScalar **a, PetscMemType *mtype)
1576: {
1577:   Mat_SeqAIJHIPSPARSE *cusp;
1578:   CsrMatrix           *matrix;

1580:   PetscFunctionBegin;
1581:   PetscCall(MatSeqAIJHIPSPARSECopyToGPU(A));
1582:   PetscCheck(A->factortype == MAT_FACTOR_NONE, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
1583:   cusp = static_cast<Mat_SeqAIJHIPSPARSE *>(A->spptr);
1584:   PetscCheck(cusp != NULL, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONGSTATE, "cusp is NULL");
1585:   matrix = (CsrMatrix *)cusp->mat->mat;

1587:   if (i) *i = matrix->row_offsets->data().get();
1588:   if (j) *j = matrix->column_indices->data().get();
1589:   if (a) *a = matrix->values->data().get();
1590:   if (mtype) *mtype = PETSC_MEMTYPE_HIP;
1591:   PetscFunctionReturn(PETSC_SUCCESS);
1592: }

1594: PETSC_INTERN PetscErrorCode MatSeqAIJHIPSPARSECopyToGPU(Mat A)
1595: {
1596:   Mat_SeqAIJHIPSPARSE           *hipsparsestruct = (Mat_SeqAIJHIPSPARSE *)A->spptr;
1597:   Mat_SeqAIJHIPSPARSEMultStruct *matstruct       = hipsparsestruct->mat;
1598:   Mat_SeqAIJ                    *a               = (Mat_SeqAIJ *)A->data;
1599:   PetscInt                       m               = A->rmap->n, *ii, *ridx, tmp;
1600:   PetscBool                      both            = PETSC_TRUE;
1601:   PetscDeviceContext             dctx;
1602:   hipStream_t                    stream;

1604:   PetscFunctionBegin;
1605:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetHandles_(&dctx, &stream));
1606:   PetscCheck(!A->boundtocpu, PETSC_COMM_SELF, PETSC_ERR_GPU, "Cannot copy to GPU");
1607:   if (A->offloadmask == PETSC_OFFLOAD_UNALLOCATED || A->offloadmask == PETSC_OFFLOAD_CPU) {
1608:     if (A->nonzerostate == hipsparsestruct->nonzerostate && hipsparsestruct->format == MAT_HIPSPARSE_CSR) { /* Copy values only */
1609:       CsrMatrix *matrix;
1610:       matrix = (CsrMatrix *)hipsparsestruct->mat->mat;

1612:       PetscCheck(!a->nz || a->a, PETSC_COMM_SELF, PETSC_ERR_GPU, "Missing CSR values");
1613:       PetscCall(PetscLogEventBegin(MAT_HIPSPARSECopyToGPU, A, 0, 0, 0));
1614:       PetscCallHIP(hipMemcpyAsync(matrix->values->data().get(), a->a, a->nz * sizeof(PetscScalar), hipMemcpyHostToDevice, stream));
1615:       PetscCall(PetscDeviceContextSynchronize(dctx));
1616:       PetscCall(PetscLogCpuToGpu(a->nz * sizeof(PetscScalar)));
1617:       PetscCall(PetscLogEventEnd(MAT_HIPSPARSECopyToGPU, A, 0, 0, 0));
1618:       PetscCall(MatSeqAIJHIPSPARSEInvalidateTranspose(A, PETSC_FALSE));
1619:     } else {
1620:       PetscInt nnz;
1621:       PetscCall(PetscLogEventBegin(MAT_HIPSPARSECopyToGPU, A, 0, 0, 0));
1622:       PetscCall(MatSeqAIJHIPSPARSEMultStruct_Destroy(&hipsparsestruct->mat, hipsparsestruct->format));
1623:       PetscCall(MatSeqAIJHIPSPARSEInvalidateTranspose(A, PETSC_TRUE));
1624:       delete hipsparsestruct->workVector;
1625:       delete hipsparsestruct->rowoffsets_gpu;
1626:       hipsparsestruct->workVector     = NULL;
1627:       hipsparsestruct->rowoffsets_gpu = NULL;
1628:       try {
1629:         if (a->compressedrow.use) {
1630:           m    = a->compressedrow.nrows;
1631:           ii   = a->compressedrow.i;
1632:           ridx = a->compressedrow.rindex;
1633:         } else {
1634:           m    = A->rmap->n;
1635:           ii   = a->i;
1636:           ridx = NULL;
1637:         }
1638:         PetscCheck(ii, PETSC_COMM_SELF, PETSC_ERR_GPU, "Missing CSR row data");
1639:         if (!a->a) {
1640:           nnz  = ii[m];
1641:           both = PETSC_FALSE;
1642:         } else nnz = a->nz;
1643:         PetscCheck(!nnz || a->j, PETSC_COMM_SELF, PETSC_ERR_GPU, "Missing CSR column data");

1645:         /* create cusparse matrix */
1646:         hipsparsestruct->nrows = m;
1647:         matstruct              = new Mat_SeqAIJHIPSPARSEMultStruct;
1648:         PetscCallHIPSPARSE(hipsparseCreateMatDescr(&matstruct->descr));
1649:         PetscCallHIPSPARSE(hipsparseSetMatIndexBase(matstruct->descr, HIPSPARSE_INDEX_BASE_ZERO));
1650:         PetscCallHIPSPARSE(hipsparseSetMatType(matstruct->descr, HIPSPARSE_MATRIX_TYPE_GENERAL));

1652:         PetscCallHIP(hipMalloc((void **)&matstruct->alpha_one, sizeof(PetscScalar)));
1653:         PetscCallHIP(hipMalloc((void **)&matstruct->beta_zero, sizeof(PetscScalar)));
1654:         PetscCallHIP(hipMalloc((void **)&matstruct->beta_one, sizeof(PetscScalar)));
1655:         PetscCallHIP(hipMemcpyAsync(matstruct->alpha_one, &PETSC_HIPSPARSE_ONE, sizeof(PetscScalar), hipMemcpyHostToDevice, stream));
1656:         PetscCallHIP(hipMemcpyAsync(matstruct->beta_zero, &PETSC_HIPSPARSE_ZERO, sizeof(PetscScalar), hipMemcpyHostToDevice, stream));
1657:         PetscCallHIP(hipMemcpyAsync(matstruct->beta_one, &PETSC_HIPSPARSE_ONE, sizeof(PetscScalar), hipMemcpyHostToDevice, stream));

1659:         /* Build a hybrid/ellpack matrix if this option is chosen for the storage */
1660:         if (hipsparsestruct->format == MAT_HIPSPARSE_CSR) {
1661:           /* set the matrix */
1662:           CsrMatrix *mat   = new CsrMatrix;
1663:           mat->num_rows    = m;
1664:           mat->num_cols    = A->cmap->n;
1665:           mat->num_entries = nnz;
1666:           PetscCallCXX(mat->row_offsets = new THRUSTINTARRAY(m + 1));
1667:           PetscCallHIP(hipMemcpyAsync(mat->row_offsets->data().get(), ii, (m + 1) * sizeof(*ii), hipMemcpyHostToDevice, stream));
1668:           PetscCallCXX(mat->column_indices = new THRUSTINTARRAY(nnz));
1669:           PetscCallHIP(hipMemcpyAsync(mat->column_indices->data().get(), a->j, (nnz) * sizeof(*a->j), hipMemcpyHostToDevice, stream));

1671:           PetscCallCXX(mat->values = new THRUSTARRAY(nnz));
1672:           if (a->a) PetscCallHIP(hipMemcpyAsync(mat->values->data().get(), a->a, (nnz) * sizeof(*a->a), hipMemcpyHostToDevice, stream));

1674:           /* assign the pointer */
1675:           matstruct->mat = mat;
1676:           if (mat->num_rows) { /* cusparse errors on empty matrices! */
1677:             PetscCallHIPSPARSE(hipsparseCreateCsr(&matstruct->matDescr, mat->num_rows, mat->num_cols, mat->num_entries, mat->row_offsets->data().get(), mat->column_indices->data().get(), mat->values->data().get(), csrRowOffsetsType, csrColIndType, HIPSPARSE_INDEX_BASE_ZERO, hipsparse_scalartype));
1678:           }
1679:         } else if (hipsparsestruct->format == MAT_HIPSPARSE_ELL || hipsparsestruct->format == MAT_HIPSPARSE_HYB) {
1680:           SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "MAT_HIPSPARSE_ELL and MAT_HIPSPARSE_HYB are not supported");
1681:         }

1683:         /* assign the compressed row indices */
1684:         if (a->compressedrow.use) {
1685:           PetscCallCXX(hipsparsestruct->workVector = new THRUSTARRAY(m));
1686:           PetscCallCXX(matstruct->cprowIndices = new THRUSTINTARRAY(m));
1687:           PetscCallHIP(hipMemcpyAsync(matstruct->cprowIndices->data().get(), ridx, (m) * sizeof(*ridx), hipMemcpyHostToDevice, stream));
1688:           tmp = m;
1689:         } else {
1690:           hipsparsestruct->workVector = NULL;
1691:           matstruct->cprowIndices     = NULL;
1692:           tmp                         = 0;
1693:         }
1694:         PetscCall(PetscLogCpuToGpu(((m + 1) + (a->nz)) * sizeof(int) + tmp * sizeof(PetscInt) + (3 + (a->nz)) * sizeof(PetscScalar)));

1696:         /* assign the pointer */
1697:         hipsparsestruct->mat = matstruct;
1698:       } catch (char *ex) {
1699:         SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "HIPSPARSE error: %s", ex);
1700:       }
1701:       PetscCall(PetscDeviceContextSynchronize(dctx));
1702:       PetscCall(PetscLogEventEnd(MAT_HIPSPARSECopyToGPU, A, 0, 0, 0));
1703:       hipsparsestruct->nonzerostate = A->nonzerostate;
1704:     }
1705:     if (both) A->offloadmask = PETSC_OFFLOAD_BOTH;
1706:   }
1707:   PetscFunctionReturn(PETSC_SUCCESS);
1708: }

1710: struct VecHIPPlusEquals {
1711:   template <typename Tuple>
1712:   __host__ __device__ void operator()(Tuple t)
1713:   {
1714:     thrust::get<1>(t) = thrust::get<1>(t) + thrust::get<0>(t);
1715:   }
1716: };

1718: struct VecHIPEquals {
1719:   template <typename Tuple>
1720:   __host__ __device__ void operator()(Tuple t)
1721:   {
1722:     thrust::get<1>(t) = thrust::get<0>(t);
1723:   }
1724: };

1726: struct VecHIPEqualsReverse {
1727:   template <typename Tuple>
1728:   __host__ __device__ void operator()(Tuple t)
1729:   {
1730:     thrust::get<0>(t) = thrust::get<1>(t);
1731:   }
1732: };

1734: struct MatProductCtx_MatMatHipsparse {
1735:   PetscBool              cisdense;
1736:   PetscScalar           *Bt;
1737:   Mat                    X;
1738:   PetscBool              reusesym; /* Hipsparse does not have split symbolic and numeric phases for sparse matmat operations */
1739:   PetscLogDouble         flops;
1740:   CsrMatrix             *Bcsr;
1741:   hipsparseSpMatDescr_t  matSpBDescr;
1742:   PetscBool              initialized; /* C = alpha op(A) op(B) + beta C */
1743:   hipsparseDnMatDescr_t  matBDescr;
1744:   hipsparseDnMatDescr_t  matCDescr;
1745:   PetscInt               Blda, Clda; /* Record leading dimensions of B and C here to detect changes*/
1746:   void                  *dBuffer4, *dBuffer5;
1747:   size_t                 mmBufferSize;
1748:   void                  *mmBuffer, *mmBuffer2; /* SpGEMM WorkEstimation buffer */
1749:   hipsparseSpGEMMDescr_t spgemmDesc;
1750: };

1752: static PetscErrorCode MatProductCtxDestroy_MatMatHipsparse(PetscCtxRt data)
1753: {
1754:   MatProductCtx_MatMatHipsparse *mmdata = *(MatProductCtx_MatMatHipsparse **)data;

1756:   PetscFunctionBegin;
1757:   PetscCallHIP(hipFree(mmdata->Bt));
1758:   delete mmdata->Bcsr;
1759:   if (mmdata->matSpBDescr) PetscCallHIPSPARSE(hipsparseDestroySpMat(mmdata->matSpBDescr));
1760:   if (mmdata->matBDescr) PetscCallHIPSPARSE(hipsparseDestroyDnMat(mmdata->matBDescr));
1761:   if (mmdata->matCDescr) PetscCallHIPSPARSE(hipsparseDestroyDnMat(mmdata->matCDescr));
1762:   if (mmdata->spgemmDesc) PetscCallHIPSPARSE(hipsparseSpGEMM_destroyDescr(mmdata->spgemmDesc));
1763:   PetscCallHIP(hipFree(mmdata->dBuffer4));
1764:   PetscCallHIP(hipFree(mmdata->dBuffer5));
1765:   PetscCallHIP(hipFree(mmdata->mmBuffer));
1766:   PetscCallHIP(hipFree(mmdata->mmBuffer2));
1767:   PetscCall(MatDestroy(&mmdata->X));
1768:   PetscCall(PetscFree(*(void **)data));
1769:   PetscFunctionReturn(PETSC_SUCCESS);
1770: }

1772: static PetscErrorCode MatProductNumeric_SeqAIJHIPSPARSE_SeqDENSEHIP(Mat C)
1773: {
1774:   Mat_Product                   *product = C->product;
1775:   Mat                            A, B;
1776:   PetscInt                       m, n, blda, clda;
1777:   PetscBool                      flg, biship, compressed;
1778:   Mat_SeqAIJ                    *a;
1779:   Mat_SeqAIJHIPSPARSE           *cusp;
1780:   hipsparseOperation_t           opA;
1781:   const PetscScalar             *barray;
1782:   PetscScalar                   *carray;
1783:   MatProductCtx_MatMatHipsparse *mmdata;
1784:   Mat_SeqAIJHIPSPARSEMultStruct *mat;
1785:   CsrMatrix                     *csrmat;
1786:   PetscDeviceContext             dctx;
1787:   hipStream_t                    stream;
1788:   hipsparseHandle_t              handle;

1790:   PetscFunctionBegin;
1791:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetSparseHandles_(&dctx, &handle, &stream));
1792:   {
1793:     const SparsePointerModeGuard pointer_mode{handle, HIPSPARSE_POINTER_MODE_DEVICE};

1795:     MatCheckProduct(C, 1);
1796:     PetscCheck(C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Product data empty");
1797:     mmdata = (MatProductCtx_MatMatHipsparse *)product->data;
1798:     A      = product->A;
1799:     B      = product->B;
1800:     PetscCall(PetscObjectTypeCompare((PetscObject)A, MATSEQAIJHIPSPARSE, &flg));
1801:     PetscCheck(flg, PetscObjectComm((PetscObject)A), PETSC_ERR_GPU, "Not for type %s", ((PetscObject)A)->type_name);
1802:     /* currently CopyToGpu does not copy if the matrix is bound to CPU
1803:        Instead of silently accepting the wrong answer, I prefer to raise the error */
1804:     PetscCheck(!A->boundtocpu, PetscObjectComm((PetscObject)A), PETSC_ERR_ARG_WRONG, "Cannot bind to CPU a HIPSPARSE matrix between MatProductSymbolic and MatProductNumeric phases");
1805:     PetscCall(MatSeqAIJHIPSPARSECopyToGPU(A));
1806:     a    = (Mat_SeqAIJ *)A->data;
1807:     cusp = (Mat_SeqAIJHIPSPARSE *)A->spptr;
1808:     switch (product->type) {
1809:     case MATPRODUCT_AB:
1810:     case MATPRODUCT_PtAP:
1811:       mat = cusp->mat;
1812:       opA = HIPSPARSE_OPERATION_NON_TRANSPOSE;
1813:       m   = A->rmap->n;
1814:       n   = B->cmap->n;
1815:       break;
1816:     case MATPRODUCT_AtB:
1817:       if (!A->form_explicit_transpose) {
1818:         mat = cusp->mat;
1819:         opA = HIPSPARSE_OPERATION_TRANSPOSE;
1820:       } else {
1821:         PetscCall(MatSeqAIJHIPSPARSEFormExplicitTranspose(A));
1822:         mat = cusp->matTranspose;
1823:         opA = HIPSPARSE_OPERATION_NON_TRANSPOSE;
1824:       }
1825:       m = A->cmap->n;
1826:       n = B->cmap->n;
1827:       break;
1828:     case MATPRODUCT_ABt:
1829:     case MATPRODUCT_RARt:
1830:       mat = cusp->mat;
1831:       opA = HIPSPARSE_OPERATION_NON_TRANSPOSE;
1832:       m   = A->rmap->n;
1833:       n   = B->rmap->n;
1834:       break;
1835:     default:
1836:       SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Unsupported product type %s", MatProductTypes[product->type]);
1837:     }
1838:     PetscCheck(mat, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Missing Mat_SeqAIJHIPSPARSEMultStruct");
1839:     csrmat = (CsrMatrix *)mat->mat;
1840:     /* when the rows of A are compressed on the device, csrmat holds only the nonempty rows of A, so the
1841:        SpMM descriptor below must be built with the full row offsets instead of those of csrmat */
1842:     compressed = (PetscBool)(mat->cprowIndices != NULL);
1843:     /* if the user passed a CPU matrix, copy the data to the GPU */
1844:     PetscCall(PetscObjectTypeCompare((PetscObject)B, MATSEQDENSEHIP, &biship));
1845:     if (!biship) PetscCall(MatConvert(B, MATSEQDENSEHIP, MAT_INPLACE_MATRIX, &B));
1846:     PetscCall(MatDenseGetArrayReadAndMemType(B, &barray, nullptr));
1847:     PetscCall(MatDenseGetLDA(B, &blda));
1848:     if (product->type == MATPRODUCT_RARt || product->type == MATPRODUCT_PtAP) {
1849:       PetscCall(MatDenseGetArrayWriteAndMemType(mmdata->X, &carray, nullptr));
1850:       PetscCall(MatDenseGetLDA(mmdata->X, &clda));
1851:     } else {
1852:       PetscCall(MatDenseGetArrayWriteAndMemType(C, &carray, nullptr));
1853:       PetscCall(MatDenseGetLDA(C, &clda));
1854:     }

1856:     PetscCall(PetscLogGpuTimeBegin());
1857:     hipsparseOperation_t opB = (product->type == MATPRODUCT_ABt || product->type == MATPRODUCT_RARt) ? HIPSPARSE_OPERATION_TRANSPOSE : HIPSPARSE_OPERATION_NON_TRANSPOSE;
1858:     /* mat->matDescr is also used by the SpGEMM code, which relies on its compressed dimensions, so when A is
1859:        compressed the SpMM needs a descriptor of its own */
1860:     hipsparseSpMatDescr_t &matADescr = compressed ? mat->matDescr_SpMM[opA] : mat->matDescr;
1861:     /* (re)allocate mmBuffer if not initialized or LDAs are different */
1862:     if (!mmdata->initialized || mmdata->Blda != blda || mmdata->Clda != clda) {
1863:       size_t mmBufferSize;
1864:       if (mmdata->initialized && mmdata->Blda != blda) {
1865:         PetscCallHIPSPARSE(hipsparseDestroyDnMat(mmdata->matBDescr));
1866:         mmdata->matBDescr = NULL;
1867:       }
1868:       if (!mmdata->matBDescr) {
1869:         PetscCallHIPSPARSE(hipsparseCreateDnMat(&mmdata->matBDescr, B->rmap->n, B->cmap->n, blda, (void *)barray, hipsparse_scalartype, HIPSPARSE_ORDER_COL));
1870:         mmdata->Blda = blda;
1871:       }
1872:       if (mmdata->initialized && mmdata->Clda != clda) {
1873:         PetscCallHIPSPARSE(hipsparseDestroyDnMat(mmdata->matCDescr));
1874:         mmdata->matCDescr = NULL;
1875:       }
1876:       if (!mmdata->matCDescr) { /* matCDescr is for C or mmdata->X */
1877:         PetscCallHIPSPARSE(hipsparseCreateDnMat(&mmdata->matCDescr, m, n, clda, (void *)carray, hipsparse_scalartype, HIPSPARSE_ORDER_COL));
1878:         mmdata->Clda = clda;
1879:       }
1880:       if (!matADescr) {
1881:         if (compressed) {
1882:           if (!cusp->rowoffsets_gpu) { /* the full row offsets may be absent when we did not construct the transpose with csr2csc */
1883:             cusp->rowoffsets_gpu = new THRUSTINTARRAY(A->rmap->n + 1);
1884:             PetscCallHIP(hipMemcpyAsync(cusp->rowoffsets_gpu->data().get(), a->i, (A->rmap->n + 1) * sizeof(*a->i), hipMemcpyHostToDevice, stream));
1885:             PetscCall(PetscDeviceContextSynchronize(dctx));
1886:             PetscCall(PetscLogCpuToGpu((A->rmap->n + 1) * sizeof(PetscInt)));
1887:           }
1888:           PetscCallHIPSPARSE(hipsparseCreateCsr(&matADescr, A->rmap->n, csrmat->num_cols, csrmat->num_entries, cusp->rowoffsets_gpu->data().get(), csrmat->column_indices->data().get(), csrmat->values->data().get(), csrRowOffsetsType, csrColIndType, HIPSPARSE_INDEX_BASE_ZERO, hipsparse_scalartype));
1889:         } else {
1890:           PetscCallHIPSPARSE(hipsparseCreateCsr(&matADescr, csrmat->num_rows, csrmat->num_cols, csrmat->num_entries, csrmat->row_offsets->data().get(), csrmat->column_indices->data().get(), csrmat->values->data().get(), csrRowOffsetsType, csrColIndType, HIPSPARSE_INDEX_BASE_ZERO, hipsparse_scalartype));
1891:         }
1892:       }
1893:       PetscCallHIPSPARSE(hipsparseSpMM_bufferSize(handle, opA, opB, mat->alpha_one, matADescr, mmdata->matBDescr, mat->beta_zero, mmdata->matCDescr, hipsparse_scalartype, cusp->spmmAlg, &mmBufferSize));
1894:       if ((mmdata->mmBuffer && mmdata->mmBufferSize < mmBufferSize) || !mmdata->mmBuffer) {
1895:         PetscCallHIP(hipFree(mmdata->mmBuffer));
1896:         PetscCallHIP(hipMalloc(&mmdata->mmBuffer, mmBufferSize));
1897:         mmdata->mmBufferSize = mmBufferSize;
1898:       }
1899:       mmdata->initialized = PETSC_TRUE;
1900:     } else {
1901:       /* to be safe, always update pointers of the mats */
1902:       PetscCallHIPSPARSE(hipsparseSpMatSetValues(matADescr, csrmat->values->data().get()));
1903:       PetscCallHIPSPARSE(hipsparseDnMatSetValues(mmdata->matBDescr, (void *)barray));
1904:       PetscCallHIPSPARSE(hipsparseDnMatSetValues(mmdata->matCDescr, (void *)carray));
1905:     }

1907:     /* do hipsparseSpMM, which supports transpose on B */
1908:     PetscCallHIPSPARSE(hipsparseSpMM(handle, opA, opB, mat->alpha_one, matADescr, mmdata->matBDescr, mat->beta_zero, mmdata->matCDescr, hipsparse_scalartype, cusp->spmmAlg, mmdata->mmBuffer));

1910:     PetscCall(PetscLogGpuTimeEnd());
1911:     PetscCall(PetscLogGpuFlops(n * 2.0 * csrmat->num_entries));
1912:     PetscCall(MatDenseRestoreArrayReadAndMemType(B, &barray));
1913:     if (product->type == MATPRODUCT_RARt) {
1914:       PetscCall(MatDenseRestoreArrayWriteAndMemType(mmdata->X, &carray));
1915:       PetscCall(MatMatMultNumeric_SeqDenseHIP_SeqDenseHIP_Internal(B, mmdata->X, C, PETSC_FALSE, PETSC_FALSE));
1916:     } else if (product->type == MATPRODUCT_PtAP) {
1917:       PetscCall(MatDenseRestoreArrayWriteAndMemType(mmdata->X, &carray));
1918:       PetscCall(MatMatMultNumeric_SeqDenseHIP_SeqDenseHIP_Internal(B, mmdata->X, C, PETSC_TRUE, PETSC_FALSE));
1919:     } else PetscCall(MatDenseRestoreArrayWriteAndMemType(C, &carray));
1920:     if (mmdata->cisdense) PetscCall(MatConvert(C, MATSEQDENSE, MAT_INPLACE_MATRIX, &C));
1921:     if (!biship) PetscCall(MatConvert(B, MATSEQDENSE, MAT_INPLACE_MATRIX, &B));
1922:     PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
1923:   }
1924:   PetscFunctionReturn(PETSC_SUCCESS);
1925: }

1927: static PetscErrorCode MatProductSymbolic_SeqAIJHIPSPARSE_SeqDENSEHIP(Mat C)
1928: {
1929:   Mat_Product                   *product = C->product;
1930:   Mat                            A, B;
1931:   PetscInt                       m, n;
1932:   PetscBool                      cisdense, flg;
1933:   MatProductCtx_MatMatHipsparse *mmdata;
1934:   Mat_SeqAIJHIPSPARSE           *cusp;

1936:   PetscFunctionBegin;
1937:   MatCheckProduct(C, 1);
1938:   PetscCheck(!C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Product data not empty");
1939:   A = product->A;
1940:   B = product->B;
1941:   PetscCall(PetscObjectTypeCompare((PetscObject)A, MATSEQAIJHIPSPARSE, &flg));
1942:   PetscCheck(flg, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Not for type %s", ((PetscObject)A)->type_name);
1943:   cusp = (Mat_SeqAIJHIPSPARSE *)A->spptr;
1944:   PetscCheck(cusp->format == MAT_HIPSPARSE_CSR, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Only for MAT_HIPSPARSE_CSR format");
1945:   switch (product->type) {
1946:   case MATPRODUCT_AB:
1947:     m = A->rmap->n;
1948:     n = B->cmap->n;
1949:     break;
1950:   case MATPRODUCT_AtB:
1951:     m = A->cmap->n;
1952:     n = B->cmap->n;
1953:     break;
1954:   case MATPRODUCT_ABt:
1955:     m = A->rmap->n;
1956:     n = B->rmap->n;
1957:     break;
1958:   case MATPRODUCT_PtAP:
1959:     m = B->cmap->n;
1960:     n = B->cmap->n;
1961:     break;
1962:   case MATPRODUCT_RARt:
1963:     m = B->rmap->n;
1964:     n = B->rmap->n;
1965:     break;
1966:   default:
1967:     SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Unsupported product type %s", MatProductTypes[product->type]);
1968:   }
1969:   PetscCall(MatSetSizes(C, m, n, m, n));
1970:   /* if C is of type MATSEQDENSE (CPU), perform the operation on the GPU and then copy on the CPU */
1971:   PetscCall(PetscObjectTypeCompare((PetscObject)C, MATSEQDENSE, &cisdense));
1972:   PetscCall(MatSetType(C, MATSEQDENSEHIP));
1973:   /* keep the VecType of B, e.g. VECKOKKOS from MatCreateDenseFromVecType(), but only if B is a MATSEQDENSEHIP like C, since the VecType of a MATSEQDENSE B, e.g. VECSTANDARD, is not valid for C */
1974:   PetscCall(PetscObjectTypeCompare((PetscObject)B, MATSEQDENSEHIP, &flg));
1975:   if (flg) PetscCall(MatSetVecType(C, B->defaultvectype));

1977:   /* product data */
1978:   PetscCall(PetscNew(&mmdata));
1979:   mmdata->cisdense = cisdense;
1980:   /* for these products we need intermediate storage */
1981:   if (product->type == MATPRODUCT_RARt || product->type == MATPRODUCT_PtAP) {
1982:     PetscCall(MatCreate(PetscObjectComm((PetscObject)C), &mmdata->X));
1983:     PetscCall(MatSetType(mmdata->X, MATSEQDENSEHIP));
1984:     /* do not preallocate, since the first call to MatDenseHIPGetArray will preallocate on the GPU for us */
1985:     if (product->type == MATPRODUCT_RARt) PetscCall(MatSetSizes(mmdata->X, A->rmap->n, B->rmap->n, A->rmap->n, B->rmap->n));
1986:     else PetscCall(MatSetSizes(mmdata->X, A->rmap->n, B->cmap->n, A->rmap->n, B->cmap->n));
1987:   }
1988:   C->product->data       = mmdata;
1989:   C->product->destroy    = MatProductCtxDestroy_MatMatHipsparse;
1990:   C->ops->productnumeric = MatProductNumeric_SeqAIJHIPSPARSE_SeqDENSEHIP;
1991:   PetscFunctionReturn(PETSC_SUCCESS);
1992: }

1994: static PetscErrorCode MatProductNumeric_SeqAIJHIPSPARSE_SeqAIJHIPSPARSE(Mat C)
1995: {
1996:   Mat_Product                   *product = C->product;
1997:   Mat                            A, B;
1998:   Mat_SeqAIJHIPSPARSE           *Acusp, *Bcusp, *Ccusp;
1999:   Mat_SeqAIJ                    *c = (Mat_SeqAIJ *)C->data;
2000:   Mat_SeqAIJHIPSPARSEMultStruct *Amat, *Bmat, *Cmat;
2001:   CsrMatrix                     *Acsr, *Bcsr, *Ccsr;
2002:   PetscBool                      flg;
2003:   MatProductType                 ptype;
2004:   MatProductCtx_MatMatHipsparse *mmdata;
2005:   hipsparseSpMatDescr_t          BmatSpDescr;
2006:   hipsparseOperation_t           opA = HIPSPARSE_OPERATION_NON_TRANSPOSE, opB = HIPSPARSE_OPERATION_NON_TRANSPOSE; /* hipSPARSE spgemm doesn't support transpose yet */
2007:   PetscDeviceContext             dctx;
2008:   hipsparseHandle_t              handle;

2010:   PetscFunctionBegin;
2011:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetSparseHandles_(&dctx, &handle));
2012:   {
2013:     const SparsePointerModeGuard pointer_mode{handle, HIPSPARSE_POINTER_MODE_DEVICE};

2015:     MatCheckProduct(C, 1);
2016:     PetscCheck(C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Product data empty");
2017:     PetscCall(PetscObjectTypeCompare((PetscObject)C, MATSEQAIJHIPSPARSE, &flg));
2018:     PetscCheck(flg, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Not for C of type %s", ((PetscObject)C)->type_name);
2019:     mmdata = (MatProductCtx_MatMatHipsparse *)C->product->data;
2020:     A      = product->A;
2021:     B      = product->B;
2022:     if (mmdata->reusesym) { /* this happens when api_user is true, meaning that the matrix values have been already computed in the MatProductSymbolic phase */
2023:       mmdata->reusesym = PETSC_FALSE;
2024:       Ccusp            = (Mat_SeqAIJHIPSPARSE *)C->spptr;
2025:       PetscCheck(Ccusp->format == MAT_HIPSPARSE_CSR, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Only for MAT_HIPSPARSE_CSR format");
2026:       Cmat = Ccusp->mat;
2027:       PetscCheck(Cmat, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Missing C mult struct for product type %s", MatProductTypes[C->product->type]);
2028:       Ccsr = (CsrMatrix *)Cmat->mat;
2029:       PetscCheck(Ccsr, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Missing C CSR struct");
2030:       goto finalize;
2031:     }
2032:     if (!c->nz) goto finalize;
2033:     PetscCall(PetscObjectTypeCompare((PetscObject)A, MATSEQAIJHIPSPARSE, &flg));
2034:     PetscCheck(flg, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Not for type %s", ((PetscObject)A)->type_name);
2035:     PetscCall(PetscObjectTypeCompare((PetscObject)B, MATSEQAIJHIPSPARSE, &flg));
2036:     PetscCheck(flg, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Not for B of type %s", ((PetscObject)B)->type_name);
2037:     PetscCheck(!A->boundtocpu, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONG, "Cannot bind to CPU a HIPSPARSE matrix between MatProductSymbolic and MatProductNumeric phases");
2038:     PetscCheck(!B->boundtocpu, PetscObjectComm((PetscObject)C), PETSC_ERR_ARG_WRONG, "Cannot bind to CPU a HIPSPARSE matrix between MatProductSymbolic and MatProductNumeric phases");
2039:     Acusp = (Mat_SeqAIJHIPSPARSE *)A->spptr;
2040:     Bcusp = (Mat_SeqAIJHIPSPARSE *)B->spptr;
2041:     Ccusp = (Mat_SeqAIJHIPSPARSE *)C->spptr;
2042:     PetscCheck(Acusp->format == MAT_HIPSPARSE_CSR, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Only for MAT_HIPSPARSE_CSR format");
2043:     PetscCheck(Bcusp->format == MAT_HIPSPARSE_CSR, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Only for MAT_HIPSPARSE_CSR format");
2044:     PetscCheck(Ccusp->format == MAT_HIPSPARSE_CSR, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Only for MAT_HIPSPARSE_CSR format");
2045:     PetscCall(MatSeqAIJHIPSPARSECopyToGPU(A));
2046:     PetscCall(MatSeqAIJHIPSPARSECopyToGPU(B));

2048:     ptype = product->type;
2049:     if (A->symmetric == PETSC_BOOL3_TRUE && ptype == MATPRODUCT_AtB) {
2050:       ptype = MATPRODUCT_AB;
2051:       PetscCheck(product->symbolic_used_the_fact_A_is_symmetric, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Symbolic should have been built using the fact that A is symmetric");
2052:     }
2053:     if (B->symmetric == PETSC_BOOL3_TRUE && ptype == MATPRODUCT_ABt) {
2054:       ptype = MATPRODUCT_AB;
2055:       PetscCheck(product->symbolic_used_the_fact_B_is_symmetric, PetscObjectComm((PetscObject)C), PETSC_ERR_PLIB, "Symbolic should have been built using the fact that B is symmetric");
2056:     }
2057:     switch (ptype) {
2058:     case MATPRODUCT_AB:
2059:       Amat = Acusp->mat;
2060:       Bmat = Bcusp->mat;
2061:       break;
2062:     case MATPRODUCT_AtB:
2063:       PetscCall(MatSeqAIJHIPSPARSEFormExplicitTranspose(A));
2064:       Amat = Acusp->matTranspose;
2065:       Bmat = Bcusp->mat;
2066:       break;
2067:     case MATPRODUCT_ABt:
2068:       Amat = Acusp->mat;
2069:       PetscCall(MatSeqAIJHIPSPARSEFormExplicitTranspose(B));
2070:       Bmat = Bcusp->matTranspose;
2071:       break;
2072:     default:
2073:       SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Unsupported product type %s", MatProductTypes[product->type]);
2074:     }
2075:     Cmat = Ccusp->mat;
2076:     PetscCheck(Amat, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Missing A mult struct for product type %s", MatProductTypes[ptype]);
2077:     PetscCheck(Bmat, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Missing B mult struct for product type %s", MatProductTypes[ptype]);
2078:     PetscCheck(Cmat, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Missing C mult struct for product type %s", MatProductTypes[ptype]);
2079:     Acsr = (CsrMatrix *)Amat->mat;
2080:     Bcsr = mmdata->Bcsr ? mmdata->Bcsr : (CsrMatrix *)Bmat->mat; /* B may be in compressed row storage */
2081:     Ccsr = (CsrMatrix *)Cmat->mat;
2082:     PetscCheck(Acsr, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Missing A CSR struct");
2083:     PetscCheck(Bcsr, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Missing B CSR struct");
2084:     PetscCheck(Ccsr, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Missing C CSR struct");
2085:     PetscCall(PetscLogGpuTimeBegin());
2086:     BmatSpDescr = mmdata->Bcsr ? mmdata->matSpBDescr : Bmat->matDescr; /* B may be in compressed row storage */
2087:     if (c->nz) PetscCallHIPSPARSE(hipsparseSpGEMMreuse_compute(handle, opA, opB, Cmat->alpha_one, Amat->matDescr, BmatSpDescr, Cmat->beta_zero, Cmat->matDescr, hipsparse_scalartype, HIPSPARSE_SPGEMM_DEFAULT, mmdata->spgemmDesc));
2088:     PetscCall(PetscLogGpuFlops(mmdata->flops));
2089:     PetscCall(PetscDeviceContextSynchronize(dctx));
2090:     PetscCall(PetscLogGpuTimeEnd());
2091:     C->offloadmask = PETSC_OFFLOAD_GPU;
2092:   finalize:
2093:     /* shorter version of MatAssemblyEnd_SeqAIJ */
2094:     PetscCall(PetscInfo(C, "Matrix size: %" PetscInt_FMT " X %" PetscInt_FMT "; storage space: 0 unneeded, %" PetscInt_FMT " used\n", C->rmap->n, C->cmap->n, c->nz));
2095:     PetscCall(PetscInfo(C, "Number of mallocs during MatSetValues() is 0\n"));
2096:     PetscCall(PetscInfo(C, "Maximum nonzeros in any row is %" PetscInt_FMT "\n", c->rmax));
2097:     c->reallocs = 0;
2098:     C->info.mallocs += 0;
2099:     C->info.nz_unneeded = 0;
2100:     C->assembled = C->was_assembled = PETSC_TRUE;
2101:     C->num_ass++;
2102:   }
2103:   PetscFunctionReturn(PETSC_SUCCESS);
2104: }

2106: static PetscErrorCode MatProductSymbolic_SeqAIJHIPSPARSE_SeqAIJHIPSPARSE(Mat C)
2107: {
2108:   Mat_Product                   *product = C->product;
2109:   Mat                            A, B;
2110:   Mat_SeqAIJHIPSPARSE           *Acusp, *Bcusp, *Ccusp;
2111:   Mat_SeqAIJ                    *a, *b, *c;
2112:   Mat_SeqAIJHIPSPARSEMultStruct *Amat, *Bmat, *Cmat;
2113:   CsrMatrix                     *Acsr, *Bcsr, *Ccsr;
2114:   PetscInt                       i, j, m, n, k;
2115:   PetscBool                      flg;
2116:   MatProductType                 ptype;
2117:   MatProductCtx_MatMatHipsparse *mmdata;
2118:   PetscLogDouble                 flops;
2119:   PetscBool                      biscompressed, ciscompressed;
2120:   int64_t                        C_num_rows1, C_num_cols1, C_nnz1;
2121:   hipsparseSpMatDescr_t          BmatSpDescr;
2122:   hipsparseOperation_t           opA = HIPSPARSE_OPERATION_NON_TRANSPOSE, opB = HIPSPARSE_OPERATION_NON_TRANSPOSE; /* HIPSPARSE spgemm doesn't support transpose yet */
2123:   PetscDeviceContext             dctx;
2124:   hipStream_t                    stream;
2125:   hipsparseHandle_t              handle;

2127:   PetscFunctionBegin;
2128:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetSparseHandles_(&dctx, &handle, &stream));
2129:   {
2130:     const SparsePointerModeGuard pointer_mode{handle, HIPSPARSE_POINTER_MODE_DEVICE};

2132:     MatCheckProduct(C, 1);
2133:     PetscCheck(!C->product->data, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Product data not empty");
2134:     A = product->A;
2135:     B = product->B;
2136:     PetscCall(PetscObjectTypeCompare((PetscObject)A, MATSEQAIJHIPSPARSE, &flg));
2137:     PetscCheck(flg, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Not for type %s", ((PetscObject)A)->type_name);
2138:     PetscCall(PetscObjectTypeCompare((PetscObject)B, MATSEQAIJHIPSPARSE, &flg));
2139:     PetscCheck(flg, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Not for B of type %s", ((PetscObject)B)->type_name);
2140:     a = (Mat_SeqAIJ *)A->data;
2141:     b = (Mat_SeqAIJ *)B->data;
2142:     /* product data */
2143:     PetscCall(PetscNew(&mmdata));
2144:     C->product->data    = mmdata;
2145:     C->product->destroy = MatProductCtxDestroy_MatMatHipsparse;

2147:     PetscCall(MatSeqAIJHIPSPARSECopyToGPU(A));
2148:     PetscCall(MatSeqAIJHIPSPARSECopyToGPU(B));
2149:     Acusp = (Mat_SeqAIJHIPSPARSE *)A->spptr; /* Access spptr after MatSeqAIJHIPSPARSECopyToGPU, not before */
2150:     Bcusp = (Mat_SeqAIJHIPSPARSE *)B->spptr;
2151:     PetscCheck(Acusp->format == MAT_HIPSPARSE_CSR, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Only for MAT_HIPSPARSE_CSR format");
2152:     PetscCheck(Bcusp->format == MAT_HIPSPARSE_CSR, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Only for MAT_HIPSPARSE_CSR format");

2154:     ptype = product->type;
2155:     if (A->symmetric == PETSC_BOOL3_TRUE && ptype == MATPRODUCT_AtB) {
2156:       ptype                                          = MATPRODUCT_AB;
2157:       product->symbolic_used_the_fact_A_is_symmetric = PETSC_TRUE;
2158:     }
2159:     if (B->symmetric == PETSC_BOOL3_TRUE && ptype == MATPRODUCT_ABt) {
2160:       ptype                                          = MATPRODUCT_AB;
2161:       product->symbolic_used_the_fact_B_is_symmetric = PETSC_TRUE;
2162:     }
2163:     biscompressed = PETSC_FALSE;
2164:     ciscompressed = PETSC_FALSE;
2165:     switch (ptype) {
2166:     case MATPRODUCT_AB:
2167:       m    = A->rmap->n;
2168:       n    = B->cmap->n;
2169:       k    = A->cmap->n;
2170:       Amat = Acusp->mat;
2171:       Bmat = Bcusp->mat;
2172:       if (a->compressedrow.use) ciscompressed = PETSC_TRUE;
2173:       if (b->compressedrow.use) biscompressed = PETSC_TRUE;
2174:       break;
2175:     case MATPRODUCT_AtB:
2176:       m = A->cmap->n;
2177:       n = B->cmap->n;
2178:       k = A->rmap->n;
2179:       PetscCall(MatSeqAIJHIPSPARSEFormExplicitTranspose(A));
2180:       Amat = Acusp->matTranspose;
2181:       Bmat = Bcusp->mat;
2182:       if (b->compressedrow.use) biscompressed = PETSC_TRUE;
2183:       break;
2184:     case MATPRODUCT_ABt:
2185:       m = A->rmap->n;
2186:       n = B->rmap->n;
2187:       k = A->cmap->n;
2188:       PetscCall(MatSeqAIJHIPSPARSEFormExplicitTranspose(B));
2189:       Amat = Acusp->mat;
2190:       Bmat = Bcusp->matTranspose;
2191:       if (a->compressedrow.use) ciscompressed = PETSC_TRUE;
2192:       break;
2193:     default:
2194:       SETERRQ(PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Unsupported product type %s", MatProductTypes[product->type]);
2195:     }

2197:     /* create hipsparse matrix */
2198:     PetscCall(MatSetSizes(C, m, n, m, n));
2199:     PetscCall(MatSetType(C, MATSEQAIJHIPSPARSE));
2200:     c     = (Mat_SeqAIJ *)C->data;
2201:     Ccusp = (Mat_SeqAIJHIPSPARSE *)C->spptr;
2202:     Cmat  = new Mat_SeqAIJHIPSPARSEMultStruct;
2203:     Ccsr  = new CsrMatrix;

2205:     c->compressedrow.use = ciscompressed;
2206:     if (c->compressedrow.use) { /* if a is in compressed row, than c will be in compressed row format */
2207:       c->compressedrow.nrows = a->compressedrow.nrows;
2208:       PetscCall(PetscMalloc2(c->compressedrow.nrows + 1, &c->compressedrow.i, c->compressedrow.nrows, &c->compressedrow.rindex));
2209:       PetscCall(PetscArraycpy(c->compressedrow.rindex, a->compressedrow.rindex, c->compressedrow.nrows));
2210:       Ccusp->workVector  = new THRUSTARRAY(c->compressedrow.nrows);
2211:       Cmat->cprowIndices = new THRUSTINTARRAY(c->compressedrow.nrows);
2212:       PetscCallHIP(hipMemcpyAsync(Cmat->cprowIndices->data().get(), c->compressedrow.rindex, (c->compressedrow.nrows) * sizeof(*c->compressedrow.rindex), hipMemcpyHostToDevice, stream));
2213:     } else {
2214:       c->compressedrow.nrows  = 0;
2215:       c->compressedrow.i      = NULL;
2216:       c->compressedrow.rindex = NULL;
2217:       Ccusp->workVector       = NULL;
2218:       Cmat->cprowIndices      = NULL;
2219:     }
2220:     Ccusp->nrows      = ciscompressed ? c->compressedrow.nrows : m;
2221:     Ccusp->mat        = Cmat;
2222:     Ccusp->mat->mat   = Ccsr;
2223:     Ccsr->num_rows    = Ccusp->nrows;
2224:     Ccsr->num_cols    = n;
2225:     Ccsr->row_offsets = new THRUSTINTARRAY(Ccusp->nrows + 1);
2226:     PetscCallHIPSPARSE(hipsparseCreateMatDescr(&Cmat->descr));
2227:     PetscCallHIPSPARSE(hipsparseSetMatIndexBase(Cmat->descr, HIPSPARSE_INDEX_BASE_ZERO));
2228:     PetscCallHIPSPARSE(hipsparseSetMatType(Cmat->descr, HIPSPARSE_MATRIX_TYPE_GENERAL));
2229:     PetscCallHIP(hipMalloc((void **)&Cmat->alpha_one, sizeof(PetscScalar)));
2230:     PetscCallHIP(hipMalloc((void **)&Cmat->beta_zero, sizeof(PetscScalar)));
2231:     PetscCallHIP(hipMalloc((void **)&Cmat->beta_one, sizeof(PetscScalar)));
2232:     PetscCallHIP(hipMemcpyAsync(Cmat->alpha_one, &PETSC_HIPSPARSE_ONE, sizeof(PetscScalar), hipMemcpyHostToDevice, stream));
2233:     PetscCallHIP(hipMemcpyAsync(Cmat->beta_zero, &PETSC_HIPSPARSE_ZERO, sizeof(PetscScalar), hipMemcpyHostToDevice, stream));
2234:     PetscCallHIP(hipMemcpyAsync(Cmat->beta_one, &PETSC_HIPSPARSE_ONE, sizeof(PetscScalar), hipMemcpyHostToDevice, stream));
2235:     if (!Ccsr->num_rows || !Ccsr->num_cols || !a->nz || !b->nz) { /* hipsparse raise errors in different calls when matrices have zero rows/columns! */
2236:       PetscCallThrust(thrust::fill(thrust::device.on(stream), Ccsr->row_offsets->begin(), Ccsr->row_offsets->end(), 0));
2237:       c->nz                = 0;
2238:       Ccsr->column_indices = new THRUSTINTARRAY(c->nz);
2239:       Ccsr->values         = new THRUSTARRAY(c->nz);
2240:       goto finalizesym;
2241:     }

2243:     PetscCheck(Amat, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Missing A mult struct for product type %s", MatProductTypes[ptype]);
2244:     PetscCheck(Bmat, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Missing B mult struct for product type %s", MatProductTypes[ptype]);
2245:     Acsr = (CsrMatrix *)Amat->mat;
2246:     if (!biscompressed) {
2247:       Bcsr        = (CsrMatrix *)Bmat->mat;
2248:       BmatSpDescr = Bmat->matDescr;
2249:     } else { /* we need to use row offsets for the full matrix */
2250:       CsrMatrix *cBcsr     = (CsrMatrix *)Bmat->mat;
2251:       Bcsr                 = new CsrMatrix;
2252:       Bcsr->num_rows       = B->rmap->n;
2253:       Bcsr->num_cols       = cBcsr->num_cols;
2254:       Bcsr->num_entries    = cBcsr->num_entries;
2255:       Bcsr->column_indices = cBcsr->column_indices;
2256:       Bcsr->values         = cBcsr->values;
2257:       if (!Bcusp->rowoffsets_gpu) {
2258:         Bcusp->rowoffsets_gpu = new THRUSTINTARRAY(B->rmap->n + 1);
2259:         PetscCallHIP(hipMemcpyAsync(Bcusp->rowoffsets_gpu->data().get(), b->i, (B->rmap->n + 1) * sizeof(*b->i), hipMemcpyHostToDevice, stream));
2260:         PetscCall(PetscLogCpuToGpu((B->rmap->n + 1) * sizeof(PetscInt)));
2261:       }
2262:       Bcsr->row_offsets = Bcusp->rowoffsets_gpu;
2263:       mmdata->Bcsr      = Bcsr;
2264:       if (Bcsr->num_rows && Bcsr->num_cols) {
2265:         PetscCallHIPSPARSE(hipsparseCreateCsr(&mmdata->matSpBDescr, Bcsr->num_rows, Bcsr->num_cols, Bcsr->num_entries, Bcsr->row_offsets->data().get(), Bcsr->column_indices->data().get(), Bcsr->values->data().get(), csrRowOffsetsType, csrColIndType, HIPSPARSE_INDEX_BASE_ZERO, hipsparse_scalartype));
2266:       }
2267:       BmatSpDescr = mmdata->matSpBDescr;
2268:     }
2269:     PetscCheck(Acsr, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Missing A CSR struct");
2270:     PetscCheck(Bcsr, PetscObjectComm((PetscObject)C), PETSC_ERR_GPU, "Missing B CSR struct");
2271:     /* precompute flops count */
2272:     if (ptype == MATPRODUCT_AB) {
2273:       for (i = 0, flops = 0; i < A->rmap->n; i++) {
2274:         const PetscInt st = a->i[i];
2275:         const PetscInt en = a->i[i + 1];
2276:         for (j = st; j < en; j++) {
2277:           const PetscInt brow = a->j[j];
2278:           flops += 2. * (b->i[brow + 1] - b->i[brow]);
2279:         }
2280:       }
2281:     } else if (ptype == MATPRODUCT_AtB) {
2282:       for (i = 0, flops = 0; i < A->rmap->n; i++) {
2283:         const PetscInt anzi = a->i[i + 1] - a->i[i];
2284:         const PetscInt bnzi = b->i[i + 1] - b->i[i];
2285:         flops += (2. * anzi) * bnzi;
2286:       }
2287:     } else flops = 0.; /* TODO */

2289:     mmdata->flops = flops;
2290:     PetscCall(PetscLogGpuTimeBegin());

2292:     // cuSparse first had cusparseSpGEMM_compute(), then had cusparseSpGEMMreuse_compute(). But NVIDIA deprecated cusparseSpGEMMreuse_compute()
2293:     // later and went back to cusparseSpGEMM_compute(). AMD followed suit. However, hipsparseSpGEMM_compute() is correct on rocm-5.4.3 but buggy
2294:     // in rocm-6.2 and 7.2. Second call to hipsparseSpGEMM_compute() gives stale result with updated input matrices.
2295:     // See https://github.com/ROCm/rocm-libraries/issues/8878. So we will use the _reuse version until AMD fixes the bug.
2296:     {
2297:       PetscCallHIPSPARSE(hipsparseCreateCsr(&Cmat->matDescr, Ccsr->num_rows, Ccsr->num_cols, 0, Ccsr->row_offsets->data().get(), NULL, NULL, csrRowOffsetsType, csrColIndType, HIPSPARSE_INDEX_BASE_ZERO, hipsparse_scalartype));
2298:       PetscCallHIPSPARSE(hipsparseSpGEMM_createDescr(&mmdata->spgemmDesc));

2300:       /* hipsparseSpGEMMreuse has more reasonable APIs than hipsparseSpGEMM, so we prefer to use it.
2301:        We follow the sample code at https://github.com/ROCmSoftwarePlatform/hipSPARSE/blob/develop/clients/include/testing_spgemmreuse_csr.hpp
2302:     */
2303:       void *dBuffer1 = NULL;
2304:       void *dBuffer2 = NULL;
2305:       void *dBuffer3 = NULL;
2306:       /* dBuffer4, dBuffer5 are needed by hipsparseSpGEMMreuse_compute, and therefore are stored in mmdata */
2307:       size_t bufferSize1 = 0;
2308:       size_t bufferSize2 = 0;
2309:       size_t bufferSize3 = 0;
2310:       size_t bufferSize4 = 0;
2311:       size_t bufferSize5 = 0;

2313:       /* ask bufferSize1 bytes for external memory */
2314:       PetscCallHIPSPARSE(hipsparseSpGEMMreuse_workEstimation(handle, opA, opB, Amat->matDescr, BmatSpDescr, Cmat->matDescr, HIPSPARSE_SPGEMM_DEFAULT, mmdata->spgemmDesc, &bufferSize1, NULL));
2315:       PetscCallHIP(hipMalloc((void **)&dBuffer1, bufferSize1));
2316:       /* inspect the matrices A and B to understand the memory requirement for the next step */
2317:       PetscCallHIPSPARSE(hipsparseSpGEMMreuse_workEstimation(handle, opA, opB, Amat->matDescr, BmatSpDescr, Cmat->matDescr, HIPSPARSE_SPGEMM_DEFAULT, mmdata->spgemmDesc, &bufferSize1, dBuffer1));

2319:       PetscCallHIPSPARSE(hipsparseSpGEMMreuse_nnz(handle, opA, opB, Amat->matDescr, BmatSpDescr, Cmat->matDescr, HIPSPARSE_SPGEMM_DEFAULT, mmdata->spgemmDesc, &bufferSize2, NULL, &bufferSize3, NULL, &bufferSize4, NULL));
2320:       PetscCallHIP(hipMalloc((void **)&dBuffer2, bufferSize2));
2321:       PetscCallHIP(hipMalloc((void **)&dBuffer3, bufferSize3));
2322:       PetscCallHIP(hipMalloc((void **)&mmdata->dBuffer4, bufferSize4));
2323:       PetscCallHIPSPARSE(hipsparseSpGEMMreuse_nnz(handle, opA, opB, Amat->matDescr, BmatSpDescr, Cmat->matDescr, HIPSPARSE_SPGEMM_DEFAULT, mmdata->spgemmDesc, &bufferSize2, dBuffer2, &bufferSize3, dBuffer3, &bufferSize4, mmdata->dBuffer4));
2324:       PetscCallHIP(hipFree(dBuffer1));
2325:       PetscCallHIP(hipFree(dBuffer2));

2327:       /* get matrix C non-zero entries C_nnz1 */
2328:       PetscCallHIPSPARSE(hipsparseSpMatGetSize(Cmat->matDescr, &C_num_rows1, &C_num_cols1, &C_nnz1));
2329:       PetscCall(PetscIntCast(C_nnz1, &c->nz));
2330:       /* allocate matrix C */
2331:       Ccsr->column_indices = new THRUSTINTARRAY(c->nz);
2332:       PetscCallHIP(hipPeekAtLastError()); /* catch out of memory errors */
2333:       Ccsr->values = new THRUSTARRAY(c->nz);
2334:       PetscCallHIP(hipPeekAtLastError()); /* catch out of memory errors */
2335:       /* update matC with the new pointers */
2336:       if (c->nz) { /* 5.5.1 has a bug with nz = 0, exposed by mat_tests_ex123_2_hypre */
2337:         PetscCallHIPSPARSE(hipsparseCsrSetPointers(Cmat->matDescr, Ccsr->row_offsets->data().get(), Ccsr->column_indices->data().get(), Ccsr->values->data().get()));

2339:         PetscCallHIPSPARSE(hipsparseSpGEMMreuse_copy(handle, opA, opB, Amat->matDescr, BmatSpDescr, Cmat->matDescr, HIPSPARSE_SPGEMM_DEFAULT, mmdata->spgemmDesc, &bufferSize5, NULL));
2340:         PetscCallHIP(hipMalloc((void **)&mmdata->dBuffer5, bufferSize5));
2341:         PetscCallHIPSPARSE(hipsparseSpGEMMreuse_copy(handle, opA, opB, Amat->matDescr, BmatSpDescr, Cmat->matDescr, HIPSPARSE_SPGEMM_DEFAULT, mmdata->spgemmDesc, &bufferSize5, mmdata->dBuffer5));
2342:         PetscCallHIPSPARSE(hipsparseSpGEMMreuse_compute(handle, opA, opB, Cmat->alpha_one, Amat->matDescr, BmatSpDescr, Cmat->beta_zero, Cmat->matDescr, hipsparse_scalartype, HIPSPARSE_SPGEMM_DEFAULT, mmdata->spgemmDesc));
2343:       }
2344:       PetscCallHIP(hipFree(dBuffer3));
2345:       PetscCall(PetscInfo(C, "Buffer sizes for type %s, result %" PetscInt_FMT " x %" PetscInt_FMT " (k %" PetscInt_FMT ", nzA %" PetscInt_FMT ", nzB %" PetscInt_FMT ", nzC %" PetscInt_FMT ") are: %ldKB %ldKB\n", MatProductTypes[ptype], m, n, k, a->nz, b->nz, c->nz, bufferSize4 / 1024, bufferSize5 / 1024));
2346:     }

2348:     PetscCall(PetscLogGpuFlops(mmdata->flops));
2349:     PetscCall(PetscLogGpuTimeEnd());
2350:   finalizesym:
2351:     c->free_a = PETSC_TRUE;
2352:     PetscCall(PetscShmgetAllocateArray(c->nz, sizeof(PetscInt), (void **)&c->j));
2353:     PetscCall(PetscShmgetAllocateArray(m + 1, sizeof(PetscInt), (void **)&c->i));
2354:     c->free_ij = PETSC_TRUE;

2356:     PetscInt *d_i = c->i;
2357:     if (ciscompressed) d_i = c->compressedrow.i;
2358:     PetscCallHIP(hipMemcpyAsync(d_i, Ccsr->row_offsets->data().get(), Ccsr->row_offsets->size() * sizeof(PetscInt), hipMemcpyDeviceToHost, stream));
2359:     PetscCallHIP(hipMemcpyAsync(c->j, Ccsr->column_indices->data().get(), Ccsr->column_indices->size() * sizeof(PetscInt), hipMemcpyDeviceToHost, stream));
2360:     PetscCall(PetscDeviceContextSynchronize(dctx));
2361:     if (ciscompressed) { /* need to expand host row offsets */
2362:       PetscInt r = 0;
2363:       c->i[0]    = 0;
2364:       for (k = 0; k < c->compressedrow.nrows; k++) {
2365:         const PetscInt next = c->compressedrow.rindex[k];
2366:         const PetscInt old  = c->compressedrow.i[k];
2367:         for (; r < next; r++) c->i[r + 1] = old;
2368:       }
2369:       for (; r < m; r++) c->i[r + 1] = c->compressedrow.i[c->compressedrow.nrows];
2370:     }
2371:     PetscCall(PetscLogGpuToCpu((Ccsr->column_indices->size() + Ccsr->row_offsets->size()) * sizeof(PetscInt)));
2372:     PetscCall(PetscMalloc1(m, &c->ilen));
2373:     PetscCall(PetscMalloc1(m, &c->imax));
2374:     c->maxnz         = c->nz;
2375:     c->nonzerorowcnt = 0;
2376:     c->rmax          = 0;
2377:     for (k = 0; k < m; k++) {
2378:       const PetscInt nn = c->i[k + 1] - c->i[k];
2379:       c->ilen[k] = c->imax[k] = nn;
2380:       c->nonzerorowcnt += (PetscInt)!!nn;
2381:       c->rmax = PetscMax(c->rmax, nn);
2382:     }
2383:     PetscCall(PetscMalloc1(c->nz, &c->a));
2384:     Ccsr->num_entries = c->nz;

2386:     C->nonzerostate++;
2387:     PetscCall(PetscLayoutSetUp(C->rmap));
2388:     PetscCall(PetscLayoutSetUp(C->cmap));
2389:     Ccusp->nonzerostate = C->nonzerostate;
2390:     C->offloadmask      = PETSC_OFFLOAD_UNALLOCATED;
2391:     C->preallocated     = PETSC_TRUE;
2392:     C->assembled        = PETSC_FALSE;
2393:     C->was_assembled    = PETSC_FALSE;
2394:     if (product->api_user && A->offloadmask == PETSC_OFFLOAD_BOTH && B->offloadmask == PETSC_OFFLOAD_BOTH) { /* flag the matrix C values as computed, so that the numeric phase will only call MatAssembly */
2395:       mmdata->reusesym = PETSC_TRUE;
2396:       C->offloadmask   = PETSC_OFFLOAD_GPU;
2397:     }
2398:     C->ops->productnumeric = MatProductNumeric_SeqAIJHIPSPARSE_SeqAIJHIPSPARSE;
2399:   }
2400:   PetscFunctionReturn(PETSC_SUCCESS);
2401: }

2403: /* handles sparse or dense B */
2404: static PetscErrorCode MatProductSetFromOptions_SeqAIJHIPSPARSE(Mat mat)
2405: {
2406:   Mat_Product *product = mat->product;
2407:   PetscBool    isdense = PETSC_FALSE, Biscusp = PETSC_FALSE, Ciscusp = PETSC_TRUE;

2409:   PetscFunctionBegin;
2410:   MatCheckProduct(mat, 1);
2411:   PetscCall(PetscObjectBaseTypeCompare((PetscObject)product->B, MATSEQDENSE, &isdense));
2412:   if (!product->A->boundtocpu && !product->B->boundtocpu) PetscCall(PetscObjectTypeCompare((PetscObject)product->B, MATSEQAIJHIPSPARSE, &Biscusp));
2413:   if (product->type == MATPRODUCT_ABC) {
2414:     Ciscusp = PETSC_FALSE;
2415:     if (!product->C->boundtocpu) PetscCall(PetscObjectTypeCompare((PetscObject)product->C, MATSEQAIJHIPSPARSE, &Ciscusp));
2416:   }
2417:   if (Biscusp && Ciscusp) { /* we can always select the CPU backend */
2418:     PetscBool usecpu = PETSC_FALSE;
2419:     switch (product->type) {
2420:     case MATPRODUCT_AB:
2421:       if (product->api_user) {
2422:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatMatMult", "Mat");
2423:         PetscCall(PetscOptionsBool("-matmatmult_backend_cpu", "Use CPU code", "MatMatMult", usecpu, &usecpu, NULL));
2424:         PetscOptionsEnd();
2425:       } else {
2426:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_AB", "Mat");
2427:         PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatMatMult", usecpu, &usecpu, NULL));
2428:         PetscOptionsEnd();
2429:       }
2430:       break;
2431:     case MATPRODUCT_AtB:
2432:       if (product->api_user) {
2433:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatTransposeMatMult", "Mat");
2434:         PetscCall(PetscOptionsBool("-mattransposematmult_backend_cpu", "Use CPU code", "MatTransposeMatMult", usecpu, &usecpu, NULL));
2435:         PetscOptionsEnd();
2436:       } else {
2437:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_AtB", "Mat");
2438:         PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatTransposeMatMult", usecpu, &usecpu, NULL));
2439:         PetscOptionsEnd();
2440:       }
2441:       break;
2442:     case MATPRODUCT_PtAP:
2443:       if (product->api_user) {
2444:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatPtAP", "Mat");
2445:         PetscCall(PetscOptionsBool("-matptap_backend_cpu", "Use CPU code", "MatPtAP", usecpu, &usecpu, NULL));
2446:         PetscOptionsEnd();
2447:       } else {
2448:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_PtAP", "Mat");
2449:         PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatPtAP", usecpu, &usecpu, NULL));
2450:         PetscOptionsEnd();
2451:       }
2452:       break;
2453:     case MATPRODUCT_RARt:
2454:       if (product->api_user) {
2455:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatRARt", "Mat");
2456:         PetscCall(PetscOptionsBool("-matrart_backend_cpu", "Use CPU code", "MatRARt", usecpu, &usecpu, NULL));
2457:         PetscOptionsEnd();
2458:       } else {
2459:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_RARt", "Mat");
2460:         PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatRARt", usecpu, &usecpu, NULL));
2461:         PetscOptionsEnd();
2462:       }
2463:       break;
2464:     case MATPRODUCT_ABC:
2465:       if (product->api_user) {
2466:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatMatMatMult", "Mat");
2467:         PetscCall(PetscOptionsBool("-matmatmatmult_backend_cpu", "Use CPU code", "MatMatMatMult", usecpu, &usecpu, NULL));
2468:         PetscOptionsEnd();
2469:       } else {
2470:         PetscOptionsBegin(PetscObjectComm((PetscObject)mat), ((PetscObject)mat)->prefix, "MatProduct_ABC", "Mat");
2471:         PetscCall(PetscOptionsBool("-mat_product_algorithm_backend_cpu", "Use CPU code", "MatMatMatMult", usecpu, &usecpu, NULL));
2472:         PetscOptionsEnd();
2473:       }
2474:       break;
2475:     default:
2476:       break;
2477:     }
2478:     if (usecpu) Biscusp = Ciscusp = PETSC_FALSE;
2479:   }
2480:   /* dispatch */
2481:   if (isdense) {
2482:     switch (product->type) {
2483:     case MATPRODUCT_AB:
2484:     case MATPRODUCT_AtB:
2485:     case MATPRODUCT_ABt:
2486:     case MATPRODUCT_PtAP:
2487:     case MATPRODUCT_RARt:
2488:       if (product->A->boundtocpu) PetscCall(MatProductSetFromOptions_SeqAIJ_SeqDense(mat));
2489:       else mat->ops->productsymbolic = MatProductSymbolic_SeqAIJHIPSPARSE_SeqDENSEHIP;
2490:       break;
2491:     case MATPRODUCT_ABC:
2492:       mat->ops->productsymbolic = MatProductSymbolic_ABC_Basic;
2493:       break;
2494:     default:
2495:       break;
2496:     }
2497:   } else if (Biscusp && Ciscusp) {
2498:     switch (product->type) {
2499:     case MATPRODUCT_AB:
2500:     case MATPRODUCT_AtB:
2501:     case MATPRODUCT_ABt:
2502:       mat->ops->productsymbolic = MatProductSymbolic_SeqAIJHIPSPARSE_SeqAIJHIPSPARSE;
2503:       break;
2504:     case MATPRODUCT_PtAP:
2505:     case MATPRODUCT_RARt:
2506:     case MATPRODUCT_ABC:
2507:       mat->ops->productsymbolic = MatProductSymbolic_ABC_Basic;
2508:       break;
2509:     default:
2510:       break;
2511:     }
2512:   } else PetscCall(MatProductSetFromOptions_SeqAIJ(mat)); /* fallback for AIJ */
2513:   PetscFunctionReturn(PETSC_SUCCESS);
2514: }

2516: static PetscErrorCode MatMult_SeqAIJHIPSPARSE(Mat A, Vec xx, Vec yy)
2517: {
2518:   PetscFunctionBegin;
2519:   PetscCall(MatMultAddKernel_SeqAIJHIPSPARSE(A, xx, NULL, yy, PETSC_FALSE, PETSC_FALSE));
2520:   PetscFunctionReturn(PETSC_SUCCESS);
2521: }

2523: static PetscErrorCode MatMultAdd_SeqAIJHIPSPARSE(Mat A, Vec xx, Vec yy, Vec zz)
2524: {
2525:   PetscFunctionBegin;
2526:   PetscCall(MatMultAddKernel_SeqAIJHIPSPARSE(A, xx, yy, zz, PETSC_FALSE, PETSC_FALSE));
2527:   PetscFunctionReturn(PETSC_SUCCESS);
2528: }

2530: static PetscErrorCode MatMultHermitianTranspose_SeqAIJHIPSPARSE(Mat A, Vec xx, Vec yy)
2531: {
2532:   PetscFunctionBegin;
2533:   PetscCall(MatMultAddKernel_SeqAIJHIPSPARSE(A, xx, NULL, yy, PETSC_TRUE, PETSC_TRUE));
2534:   PetscFunctionReturn(PETSC_SUCCESS);
2535: }

2537: static PetscErrorCode MatMultHermitianTransposeAdd_SeqAIJHIPSPARSE(Mat A, Vec xx, Vec yy, Vec zz)
2538: {
2539:   PetscFunctionBegin;
2540:   PetscCall(MatMultAddKernel_SeqAIJHIPSPARSE(A, xx, yy, zz, PETSC_TRUE, PETSC_TRUE));
2541:   PetscFunctionReturn(PETSC_SUCCESS);
2542: }

2544: static PetscErrorCode MatMultTranspose_SeqAIJHIPSPARSE(Mat A, Vec xx, Vec yy)
2545: {
2546:   PetscFunctionBegin;
2547:   PetscCall(MatMultAddKernel_SeqAIJHIPSPARSE(A, xx, NULL, yy, PETSC_TRUE, PETSC_FALSE));
2548:   PetscFunctionReturn(PETSC_SUCCESS);
2549: }

2551: __global__ static void ScatterAdd(PetscInt n, PetscInt *idx, const PetscScalar *x, PetscScalar *y)
2552: {
2553:   int i = blockIdx.x * blockDim.x + threadIdx.x;
2554:   if (i < n) y[idx[i]] += x[i];
2555: }

2557: /* z = op(A) x + y. If trans & !herm, op = ^T; if trans & herm, op = ^H; if !trans, op = no-op */
2558: static PetscErrorCode MatMultAddKernel_SeqAIJHIPSPARSE(Mat A, Vec xx, Vec yy, Vec zz, PetscBool trans, PetscBool herm)
2559: {
2560:   Mat_SeqAIJ                    *a               = (Mat_SeqAIJ *)A->data;
2561:   Mat_SeqAIJHIPSPARSE           *hipsparsestruct = (Mat_SeqAIJHIPSPARSE *)A->spptr;
2562:   Mat_SeqAIJHIPSPARSEMultStruct *matstruct;
2563:   PetscScalar                   *xarray, *zarray, *dptr, *beta, *xptr;
2564:   hipsparseOperation_t           opA = HIPSPARSE_OPERATION_NON_TRANSPOSE;
2565:   PetscBool                      compressed;
2566:   PetscInt                       nx, ny;
2567:   PetscDeviceContext             dctx;
2568:   hipStream_t                    stream;
2569:   hipsparseHandle_t              handle;

2571:   PetscFunctionBegin;
2572:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetSparseHandles_(&dctx, &handle, &stream));
2573:   {
2574:     const SparsePointerModeGuard pointer_mode{handle, HIPSPARSE_POINTER_MODE_DEVICE};

2576:     PetscCheck(!herm || trans, PetscObjectComm((PetscObject)A), PETSC_ERR_GPU, "Hermitian and not transpose not supported");
2577:     if (!a->nz) {
2578:       if (yy) PetscCall(VecSeq_HIP::Copy(yy, zz));
2579:       else PetscCall(VecSeq_HIP::Set(zz, 0));
2580:       PetscFunctionReturn(PETSC_SUCCESS);
2581:     }
2582:     /* The line below is necessary due to the operations that modify the matrix on the CPU (axpy, scale, etc) */
2583:     PetscCall(MatSeqAIJHIPSPARSECopyToGPU(A));
2584:     if (!trans) {
2585:       matstruct = (Mat_SeqAIJHIPSPARSEMultStruct *)hipsparsestruct->mat;
2586:       PetscCheck(matstruct, PetscObjectComm((PetscObject)A), PETSC_ERR_GPU, "SeqAIJHIPSPARSE does not have a 'mat' (need to fix)");
2587:     } else {
2588:       if (herm || !A->form_explicit_transpose) {
2589:         opA       = herm ? HIPSPARSE_OPERATION_CONJUGATE_TRANSPOSE : HIPSPARSE_OPERATION_TRANSPOSE;
2590:         matstruct = (Mat_SeqAIJHIPSPARSEMultStruct *)hipsparsestruct->mat;
2591:       } else {
2592:         if (!A->transupdated) PetscCall(MatSeqAIJHIPSPARSEFormExplicitTranspose(A));
2593:         matstruct = (Mat_SeqAIJHIPSPARSEMultStruct *)hipsparsestruct->matTranspose;
2594:       }
2595:     }
2596:     /* Does the matrix use compressed rows (i.e., drop zero rows)? */
2597:     compressed = matstruct->cprowIndices ? PETSC_TRUE : PETSC_FALSE;
2598:     try {
2599:       PetscCall(VecHIPGetArrayRead(xx, (const PetscScalar **)&xarray));
2600:       if (yy == zz) PetscCall(VecHIPGetArray(zz, &zarray)); /* read & write zz, so need to get up-to-date zarray on GPU */
2601:       else PetscCall(VecHIPGetArrayWrite(zz, &zarray));     /* write zz, so no need to init zarray on GPU */

2603:       PetscCall(PetscLogGpuTimeBegin());
2604:       if (opA == HIPSPARSE_OPERATION_NON_TRANSPOSE) {
2605:         /* z = A x + beta y.
2606:            If A is compressed (with less rows), then Ax is shorter than the full z, so we need a work vector to store Ax.
2607:            When A is non-compressed, and z = y, we can set beta=1 to compute y = Ax + y in one call.
2608:         */
2609:         xptr = xarray;
2610:         dptr = compressed ? hipsparsestruct->workVector->data().get() : zarray;
2611:         beta = (yy == zz && !compressed) ? matstruct->beta_one : matstruct->beta_zero;
2612:         /* Get length of x, y for y=Ax. ny might be shorter than the work vector's allocated length, since the work vector is
2613:             allocated to accommodate different uses. So we get the length info directly from mat.
2614:          */
2615:         if (hipsparsestruct->format == MAT_HIPSPARSE_CSR) {
2616:           CsrMatrix *mat = (CsrMatrix *)matstruct->mat;
2617:           nx             = mat->num_cols;
2618:           ny             = mat->num_rows;
2619:         }
2620:       } else {
2621:         /* z = A^T x + beta y
2622:            If A is compressed, then we need a work vector as the shorter version of x to compute A^T x.
2623:            Note A^Tx is of full length, so we set beta to 1.0 if y exists.
2624:          */
2625:         xptr = compressed ? hipsparsestruct->workVector->data().get() : xarray;
2626:         dptr = zarray;
2627:         beta = yy ? matstruct->beta_one : matstruct->beta_zero;
2628:         if (compressed) { /* Scatter x to work vector */
2629:           thrust::device_ptr<PetscScalar> xarr = thrust::device_pointer_cast(xarray);

2631:           PetscCallThrust(thrust::for_each(thrust::device.on(stream), thrust::make_zip_iterator(thrust::make_tuple(hipsparsestruct->workVector->begin(), thrust::make_permutation_iterator(xarr, matstruct->cprowIndices->begin()))),
2632:                                            thrust::make_zip_iterator(thrust::make_tuple(hipsparsestruct->workVector->begin(), thrust::make_permutation_iterator(xarr, matstruct->cprowIndices->begin()))) + matstruct->cprowIndices->size(), VecHIPEqualsReverse()));
2633:         }
2634:         if (hipsparsestruct->format == MAT_HIPSPARSE_CSR) {
2635:           CsrMatrix *mat = (CsrMatrix *)matstruct->mat;
2636:           nx             = mat->num_rows;
2637:           ny             = mat->num_cols;
2638:         }
2639:       }
2640:       /* csr_spmv does y = alpha op(A) x + beta y */
2641:       if (hipsparsestruct->format == MAT_HIPSPARSE_CSR) {
2642:         hipsparseSpMVAlg_t spmvAlg = hipsparsestruct->spmvAlg;

2644: #if PETSC_PKG_HIP_VERSION_GE(6, 4, 0) && PETSC_PKG_HIP_VERSION_LT(7, 3, 0) // ALG_DEFAULT in some versions don't support transpose. See https://github.com/ROCm/rocm-libraries/issues/4803
2645:         // We found rocm-7.2.4 also had this problem. We assume rocm-7.3+ will contain a fix.
2646:         if (opA != HIPSPARSE_OPERATION_NON_TRANSPOSE && spmvAlg == HIPSPARSE_SPMV_ALG_DEFAULT) spmvAlg = HIPSPARSE_SPMV_CSR_ALG1;
2647: #endif
2648:         PetscCheck(opA >= 0 && opA <= 2, PETSC_COMM_SELF, PETSC_ERR_SUP, "hipSPARSE API on hipsparseOperation_t has changed and PETSc has not been updated accordingly");

2650:         if (!matstruct->hipSpMV[opA].initialized) { /* built on demand */
2651:           CsrMatrix *mat = (CsrMatrix *)matstruct->mat;
2652:           PetscCallHIPSPARSE(hipsparseCreateCsr(&matstruct->hipSpMV[opA].matDescr, mat->num_rows, mat->num_cols, mat->num_entries, mat->row_offsets->data().get(), mat->column_indices->data().get(), mat->values->data().get(), csrRowOffsetsType, csrColIndType, HIPSPARSE_INDEX_BASE_ZERO, hipsparse_scalartype));
2653:           PetscCallHIPSPARSE(hipsparseCreateDnVec(&matstruct->hipSpMV[opA].vecXDescr, nx, xptr, hipsparse_scalartype));
2654:           PetscCallHIPSPARSE(hipsparseCreateDnVec(&matstruct->hipSpMV[opA].vecYDescr, ny, dptr, hipsparse_scalartype));
2655:           PetscCallHIPSPARSE(
2656:             hipsparseSpMV_bufferSize(handle, opA, matstruct->alpha_one, matstruct->hipSpMV[opA].matDescr, matstruct->hipSpMV[opA].vecXDescr, beta, matstruct->hipSpMV[opA].vecYDescr, hipsparse_scalartype, spmvAlg, &matstruct->hipSpMV[opA].spmvBufferSize));
2657:           PetscCallHIP(hipMalloc(&matstruct->hipSpMV[opA].spmvBuffer, matstruct->hipSpMV[opA].spmvBufferSize));
2658: #if PETSC_PKG_HIP_VERSION_GE(6, 4, 0) // hipsparseSpMV_preprocess is added in rocm-6.4.0
2659:           PetscCallHIPSPARSE(
2660:             hipsparseSpMV_preprocess(handle, opA, matstruct->alpha_one, matstruct->hipSpMV[opA].matDescr, matstruct->hipSpMV[opA].vecXDescr, beta, matstruct->hipSpMV[opA].vecYDescr, hipsparse_scalartype, spmvAlg, matstruct->hipSpMV[opA].spmvBuffer));
2661: #endif
2662:           matstruct->hipSpMV[opA].initialized = PETSC_TRUE;
2663:         } else {
2664:           /* x, y's value pointers might change between calls, but their shape is kept, so we just update pointers */
2665:           PetscCallHIPSPARSE(hipsparseDnVecSetValues(matstruct->hipSpMV[opA].vecXDescr, xptr));
2666:           PetscCallHIPSPARSE(hipsparseDnVecSetValues(matstruct->hipSpMV[opA].vecYDescr, dptr));
2667:         }
2668:         PetscCallHIPSPARSE(hipsparseSpMV(handle, opA, matstruct->alpha_one, matstruct->hipSpMV[opA].matDescr, matstruct->hipSpMV[opA].vecXDescr, beta, matstruct->hipSpMV[opA].vecYDescr, hipsparse_scalartype, spmvAlg, matstruct->hipSpMV[opA].spmvBuffer));
2669:       } else PetscCheck(hipsparsestruct->nrows == 0, PETSC_COMM_SELF, PETSC_ERR_SUP, "MAT_HIPSPARSE_ELL and MAT_HIPSPARSE_HYB are not supported");

2671:       PetscCall(PetscLogGpuTimeEnd());

2673:       if (opA == HIPSPARSE_OPERATION_NON_TRANSPOSE) {
2674:         if (yy) {                                     /* MatMultAdd: zz = A*xx + yy */
2675:           if (compressed) {                           /* A is compressed. We first copy yy to zz, then ScatterAdd the work vector to zz */
2676:             PetscCall(VecSeq_HIP::Copy(yy, zz));      /* zz = yy */
2677:           } else if (zz != yy) {                      /* A is not compressed. zz already contains A*xx, and we just need to add yy */
2678:             PetscCall(VecSeq_HIP::AXPY(zz, 1.0, yy)); /* zz += yy */
2679:           }
2680:         } else if (compressed) { /* MatMult: zz = A*xx. A is compressed, so we zero zz first, then ScatterAdd the work vector to zz */
2681:           PetscCall(VecSeq_HIP::Set(zz, 0));
2682:         }

2684:         /* ScatterAdd the result from work vector into the full vector when A is compressed */
2685:         if (compressed) {
2686:           PetscCall(PetscLogGpuTimeBegin());
2687:           /* I wanted to make this for_each asynchronous but failed. thrust::async::for_each() returns an event (internally registered)
2688:              and in the destructor of the scope, it will call hipStreamSynchronize() on this stream. One has to store all events to
2689:              prevent that. So I just add a ScatterAdd kernel.
2690:            */
2691:           PetscInt n = matstruct->cprowIndices->size();
2692:           hipLaunchKernelGGL(ScatterAdd, dim3((n + 255) / 256), dim3(256), 0, stream, n, matstruct->cprowIndices->data().get(), hipsparsestruct->workVector->data().get(), zarray);
2693:           PetscCall(PetscLogGpuTimeEnd());
2694:         }
2695:       } else {
2696:         if (yy && yy != zz) PetscCall(VecSeq_HIP::AXPY(zz, 1.0, yy)); /* zz += yy */
2697:       }
2698:       PetscCall(VecHIPRestoreArrayRead(xx, (const PetscScalar **)&xarray));
2699:       if (yy == zz) PetscCall(VecHIPRestoreArray(zz, &zarray));
2700:       else PetscCall(VecHIPRestoreArrayWrite(zz, &zarray));
2701:     } catch (char *ex) {
2702:       SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, "HIPSPARSE error: %s", ex);
2703:     }
2704:     if (yy) PetscCall(PetscLogGpuFlops(2.0 * a->nz));
2705:     else PetscCall(PetscLogGpuFlops(2.0 * a->nz - a->nonzerorowcnt));
2706:     PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
2707:   }
2708:   PetscFunctionReturn(PETSC_SUCCESS);
2709: }

2711: static PetscErrorCode MatMultTransposeAdd_SeqAIJHIPSPARSE(Mat A, Vec xx, Vec yy, Vec zz)
2712: {
2713:   PetscFunctionBegin;
2714:   PetscCall(MatMultAddKernel_SeqAIJHIPSPARSE(A, xx, yy, zz, PETSC_TRUE, PETSC_FALSE));
2715:   PetscFunctionReturn(PETSC_SUCCESS);
2716: }

2718: static PetscErrorCode MatAssemblyEnd_SeqAIJHIPSPARSE(Mat A, MatAssemblyType mode)
2719: {
2720:   PetscFunctionBegin;
2721:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::AssemblyEnd(A, mode));
2722:   PetscFunctionReturn(PETSC_SUCCESS);
2723: }

2725: /*@
2726:   MatCreateSeqAIJHIPSPARSE - Creates a sparse matrix in `MATAIJHIPSPARSE` (compressed row) format.
2727:   This matrix will ultimately pushed down to AMD GPUs and use the HIPSPARSE library for calculations.

2729:   Collective

2731:   Input Parameters:
2732: + comm - MPI communicator, set to `PETSC_COMM_SELF`
2733: . m    - number of rows
2734: . n    - number of columns
2735: . nz   - number of nonzeros per row (same for all rows), ignored if `nnz` is set
2736: - nnz  - array containing the number of nonzeros in the various rows (possibly different for each row) or `NULL`

2738:   Output Parameter:
2739: . A - the matrix

2741:   Level: intermediate

2743:   Notes:
2744:   It is recommended that one use the `MatCreate()`, `MatSetType()` and/or `MatSetFromOptions()`,
2745:   `MatXXXXSetPreallocation()` paradgm instead of this routine directly.
2746:   [MatXXXXSetPreallocation() is, for example, `MatSeqAIJSetPreallocation`]

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

2752:   Specify the preallocated storage with either `nz` or `nnz` (not both).
2753:   Set `nz` = `PETSC_DEFAULT` and `nnz` = `NULL` for PETSc to control dynamic memory
2754:   allocation.

2756: .seealso: [](ch_matrices), `Mat`, `MatCreate()`, `MatCreateAIJ()`, `MatSetValues()`, `MatSeqAIJSetColumnIndices()`, `MatCreateSeqAIJWithArrays()`, `MATSEQAIJHIPSPARSE`, `MATAIJHIPSPARSE`
2757: @*/
2758: PetscErrorCode MatCreateSeqAIJHIPSPARSE(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt nz, const PetscInt nnz[], Mat *A)
2759: {
2760:   return MatSeqAIJHIPSPARSE_CUPM_t::CreateSeqAIJ(comm, m, n, nz, nnz, A);
2761: }

2763: static PetscErrorCode MatDestroy_SeqAIJHIPSPARSE(Mat A)
2764: {
2765:   return MatSeqAIJHIPSPARSE_CUPM_t::Destroy(A);
2766: }

2768: static PetscErrorCode MatDuplicate_SeqAIJHIPSPARSE(Mat A, MatDuplicateOption cpvalues, Mat *B)
2769: {
2770:   PetscFunctionBegin;
2771:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::Duplicate(A, cpvalues, B));
2772:   PetscFunctionReturn(PETSC_SUCCESS);
2773: }

2775: static PetscErrorCode MatAXPY_SeqAIJHIPSPARSE(Mat Y, PetscScalar a, Mat X, MatStructure str)
2776: {
2777:   Mat_SeqAIJ          *x = (Mat_SeqAIJ *)X->data, *y = (Mat_SeqAIJ *)Y->data;
2778:   Mat_SeqAIJHIPSPARSE *cy;
2779:   Mat_SeqAIJHIPSPARSE *cx;
2780:   CsrMatrix           *csry, *csrx;
2781:   PetscDeviceContext   dctx;
2782:   hipStream_t          stream;
2783:   hipsparseHandle_t    handle;

2785:   PetscFunctionBegin;
2786:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetSparseHandles_(&dctx, &handle, &stream));
2787:   {
2788:     const SparsePointerModeGuard pointer_mode{handle, HIPSPARSE_POINTER_MODE_HOST};

2790:     cy = (Mat_SeqAIJHIPSPARSE *)Y->spptr;
2791:     cx = (Mat_SeqAIJHIPSPARSE *)X->spptr;
2792:     if (X->ops->axpy != Y->ops->axpy) {
2793:       PetscCall(MatSeqAIJHIPSPARSEInvalidateTranspose(Y, PETSC_FALSE));
2794:       PetscCall(MatAXPY_SeqAIJ(Y, a, X, str));
2795:       PetscFunctionReturn(PETSC_SUCCESS);
2796:     }
2797:     /* if we are here, it means both matrices are bound to GPU */
2798:     PetscCall(MatSeqAIJHIPSPARSECopyToGPU(Y));
2799:     PetscCall(MatSeqAIJHIPSPARSECopyToGPU(X));
2800:     PetscCheck(cy->format == MAT_HIPSPARSE_CSR, PetscObjectComm((PetscObject)Y), PETSC_ERR_GPU, "only MAT_HIPSPARSE_CSR supported");
2801:     PetscCheck(cx->format == MAT_HIPSPARSE_CSR, PetscObjectComm((PetscObject)X), PETSC_ERR_GPU, "only MAT_HIPSPARSE_CSR supported");
2802:     csry = (CsrMatrix *)cy->mat->mat;
2803:     csrx = (CsrMatrix *)cx->mat->mat;
2804:     /* see if we can turn this into a cublas axpy */
2805:     if (str != SAME_NONZERO_PATTERN && x->nz == y->nz && !x->compressedrow.use && !y->compressedrow.use) {
2806:       bool eq;

2808:       PetscCallThrust(eq = thrust::equal(thrust::device.on(stream), csry->row_offsets->begin(), csry->row_offsets->end(), csrx->row_offsets->begin()));
2809:       if (eq) PetscCallThrust(eq = thrust::equal(thrust::device.on(stream), csry->column_indices->begin(), csry->column_indices->end(), csrx->column_indices->begin()));
2810:       if (eq) str = SAME_NONZERO_PATTERN;
2811:     }
2812:     /* spgeam is buggy with one column */
2813:     if (Y->cmap->n == 1 && str != SAME_NONZERO_PATTERN) str = DIFFERENT_NONZERO_PATTERN;

2815: #if !PetscDefined(USE_64BIT_INDICES) // hipsparseScsrgeam2 etc. do not support 64bit indices
2816:     if (str == SUBSET_NONZERO_PATTERN) {
2817:       PetscScalar       *ay, b = 1.0;
2818:       const PetscScalar *ax;
2819:       size_t             bufferSize;
2820:       void              *buffer;

2822:       PetscCall(MatSeqAIJHIPSPARSEGetArrayRead(X, &ax));
2823:       PetscCall(MatSeqAIJHIPSPARSEGetArray(Y, &ay));
2824:       PetscCallHIPSPARSE(hipsparse_csr_spgeam_bufferSize(handle, Y->rmap->n, Y->cmap->n, &a, cx->mat->descr, x->nz, ax, csrx->row_offsets->data().get(), csrx->column_indices->data().get(), &b, cy->mat->descr, y->nz, ay, csry->row_offsets->data().get(),
2825:                                                          csry->column_indices->data().get(), cy->mat->descr, ay, csry->row_offsets->data().get(), csry->column_indices->data().get(), &bufferSize));
2826:       PetscCallHIP(hipMalloc(&buffer, bufferSize));
2827:       PetscCall(PetscLogGpuTimeBegin());
2828:       PetscCallHIPSPARSE(hipsparse_csr_spgeam(handle, Y->rmap->n, Y->cmap->n, &a, cx->mat->descr, x->nz, ax, csrx->row_offsets->data().get(), csrx->column_indices->data().get(), &b, cy->mat->descr, y->nz, ay, csry->row_offsets->data().get(),
2829:                                               csry->column_indices->data().get(), cy->mat->descr, ay, csry->row_offsets->data().get(), csry->column_indices->data().get(), buffer));
2830:       PetscCall(PetscLogGpuFlops(x->nz + y->nz));
2831:       PetscCall(PetscLogGpuTimeEnd());
2832:       PetscCallHIP(hipFree(buffer));

2834:       PetscCall(MatSeqAIJHIPSPARSERestoreArrayRead(X, &ax));
2835:       PetscCall(MatSeqAIJHIPSPARSERestoreArray(Y, &ay));
2836:     } else
2837: #endif
2838:       if (str == SAME_NONZERO_PATTERN) {
2839:       PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::AXPY_SameNZ(Y, a, X));
2840:     } else {
2841:       PetscCall(MatSeqAIJHIPSPARSEInvalidateTranspose(Y, PETSC_FALSE));
2842:       PetscCall(MatAXPY_SeqAIJ(Y, a, X, str));
2843:     }
2844:     PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
2845:   }
2846:   PetscFunctionReturn(PETSC_SUCCESS);
2847: }

2849: static PetscErrorCode MatScale_SeqAIJHIPSPARSE(Mat Y, PetscScalar a)
2850: {
2851:   PetscFunctionBegin;
2852:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::Scale(Y, a));
2853:   PetscFunctionReturn(PETSC_SUCCESS);
2854: }

2856: static PetscErrorCode MatGetDiagonal_SeqAIJHIPSPARSE(Mat A, Vec diag)
2857: {
2858:   PetscFunctionBegin;
2859:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetDiagonal(A, diag));
2860:   PetscFunctionReturn(PETSC_SUCCESS);
2861: }

2863: static PetscErrorCode MatGetRowSumAbs_SeqAIJHIPSPARSE(Mat A, Vec v)
2864: {
2865:   PetscFunctionBegin;
2866:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetRowSumAbs(A, v));
2867:   PetscFunctionReturn(PETSC_SUCCESS);
2868: }

2870: static PetscErrorCode MatDiagonalScale_SeqAIJHIPSPARSE(Mat A, Vec ll, Vec rr)
2871: {
2872:   PetscFunctionBegin;
2873:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::DiagonalScale(A, ll, rr));
2874:   PetscFunctionReturn(PETSC_SUCCESS);
2875: }

2877: static PetscErrorCode MatZeroEntries_SeqAIJHIPSPARSE(Mat A)
2878: {
2879:   PetscFunctionBegin;
2880:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::ZeroEntries(A));
2881:   PetscFunctionReturn(PETSC_SUCCESS);
2882: }

2884: static PetscErrorCode MatGetCurrentMemType_SeqAIJHIPSPARSE(Mat A, PetscMemType *m)
2885: {
2886:   PetscFunctionBegin;
2887:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetCurrentMemType(A, m));
2888:   PetscFunctionReturn(PETSC_SUCCESS);
2889: }

2891: static PetscErrorCode MatBindToCPU_SeqAIJHIPSPARSE(Mat A, PetscBool flg)
2892: {
2893:   Mat_SeqAIJ *a = (Mat_SeqAIJ *)A->data;

2895:   PetscFunctionBegin;
2896:   if (A->factortype != MAT_FACTOR_NONE) {
2897:     A->boundtocpu = flg;
2898:     PetscFunctionReturn(PETSC_SUCCESS);
2899:   }
2900:   if (flg) {
2901:     PetscCall(MatSeqAIJHIPSPARSECopyFromGPU(A));

2903:     A->ops->scale                     = MatScale_SeqAIJ;
2904:     A->ops->getdiagonal               = MatGetDiagonal_SeqAIJ;
2905:     A->ops->getrowsumabs              = MatGetRowSumAbs_SeqAIJ;
2906:     A->ops->diagonalscale             = MatDiagonalScale_SeqAIJ;
2907:     A->ops->axpy                      = MatAXPY_SeqAIJ;
2908:     A->ops->zeroentries               = MatZeroEntries_SeqAIJ;
2909:     A->ops->mult                      = MatMult_SeqAIJ;
2910:     A->ops->multadd                   = MatMultAdd_SeqAIJ;
2911:     A->ops->multtranspose             = MatMultTranspose_SeqAIJ;
2912:     A->ops->multtransposeadd          = MatMultTransposeAdd_SeqAIJ;
2913:     A->ops->multhermitiantranspose    = NULL;
2914:     A->ops->multhermitiantransposeadd = NULL;
2915:     A->ops->productsetfromoptions     = MatProductSetFromOptions_SeqAIJ;
2916:     A->ops->getcurrentmemtype         = NULL;
2917:     PetscCall(PetscMemzero(a->ops, sizeof(Mat_SeqAIJOps)));
2918:     PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSeqAIJCopySubArray_C", NULL));
2919:     PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijhipsparse_seqdensehip_C", NULL));
2920:     PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijhipsparse_seqdense_C", NULL));
2921:     PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSetPreallocationCOO_C", NULL));
2922:     PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSetValuesCOO_C", NULL));
2923:     PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijhipsparse_seqaijhipsparse_C", NULL));
2924:   } else {
2925:     A->ops->scale                     = MatScale_SeqAIJHIPSPARSE;
2926:     A->ops->getdiagonal               = MatGetDiagonal_SeqAIJHIPSPARSE;
2927:     A->ops->getrowsumabs              = MatGetRowSumAbs_SeqAIJHIPSPARSE;
2928:     A->ops->diagonalscale             = MatDiagonalScale_SeqAIJHIPSPARSE;
2929:     A->ops->axpy                      = MatAXPY_SeqAIJHIPSPARSE;
2930:     A->ops->zeroentries               = MatZeroEntries_SeqAIJHIPSPARSE;
2931:     A->ops->mult                      = MatMult_SeqAIJHIPSPARSE;
2932:     A->ops->multadd                   = MatMultAdd_SeqAIJHIPSPARSE;
2933:     A->ops->multtranspose             = MatMultTranspose_SeqAIJHIPSPARSE;
2934:     A->ops->multtransposeadd          = MatMultTransposeAdd_SeqAIJHIPSPARSE;
2935:     A->ops->multhermitiantranspose    = MatMultHermitianTranspose_SeqAIJHIPSPARSE;
2936:     A->ops->multhermitiantransposeadd = MatMultHermitianTransposeAdd_SeqAIJHIPSPARSE;
2937:     A->ops->productsetfromoptions     = MatProductSetFromOptions_SeqAIJHIPSPARSE;
2938:     A->ops->getcurrentmemtype         = MatGetCurrentMemType_SeqAIJHIPSPARSE;
2939:     a->ops->getarray                  = MatSeqAIJGetArray_SeqAIJHIPSPARSE;
2940:     a->ops->restorearray              = MatSeqAIJRestoreArray_SeqAIJHIPSPARSE;
2941:     a->ops->getarrayread              = MatSeqAIJGetArrayRead_SeqAIJHIPSPARSE;
2942:     a->ops->restorearrayread          = MatSeqAIJRestoreArrayRead_SeqAIJHIPSPARSE;
2943:     a->ops->getarraywrite             = MatSeqAIJGetArrayWrite_SeqAIJHIPSPARSE;
2944:     a->ops->restorearraywrite         = MatSeqAIJRestoreArrayWrite_SeqAIJHIPSPARSE;
2945:     a->ops->getcsrandmemtype          = MatSeqAIJGetCSRAndMemType_SeqAIJHIPSPARSE;

2947:     PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSeqAIJCopySubArray_C", MatSeqAIJCopySubArray_SeqAIJHIPSPARSE));
2948:     PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijhipsparse_seqdensehip_C", MatProductSetFromOptions_SeqAIJHIPSPARSE));
2949:     PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijhipsparse_seqdense_C", MatProductSetFromOptions_SeqAIJHIPSPARSE));
2950:     PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSetPreallocationCOO_C", MatSetPreallocationCOO_SeqAIJHIPSPARSE));
2951:     PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSetValuesCOO_C", MatSetValuesCOO_SeqAIJHIPSPARSE));
2952:     PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatProductSetFromOptions_seqaijhipsparse_seqaijhipsparse_C", MatProductSetFromOptions_SeqAIJHIPSPARSE));
2953:   }
2954:   A->boundtocpu = flg;
2955:   a->inode.use  = (flg && a->inode.size_csr) ? PETSC_TRUE : PETSC_FALSE;
2956:   PetscFunctionReturn(PETSC_SUCCESS);
2957: }

2959: PETSC_INTERN PetscErrorCode MatConvert_SeqAIJ_SeqAIJHIPSPARSE(Mat A, MatType mtype, MatReuse reuse, Mat *newmat)
2960: {
2961:   Mat B;

2963:   PetscFunctionBegin;
2964:   PetscCall(PetscDeviceInitialize(PETSC_DEVICE_HIP)); /* first use of HIPSPARSE may be via MatConvert */
2965:   if (reuse == MAT_INITIAL_MATRIX) {
2966:     PetscCall(MatDuplicate(A, MAT_COPY_VALUES, newmat));
2967:   } else if (reuse == MAT_REUSE_MATRIX) {
2968:     PetscCall(MatCopy(A, *newmat, SAME_NONZERO_PATTERN));
2969:   }
2970:   B = *newmat;
2971:   PetscCall(PetscFree(B->defaultvectype));
2972:   PetscCall(PetscStrallocpy(VECHIP, &B->defaultvectype));
2973:   if (reuse != MAT_REUSE_MATRIX && !B->spptr) {
2974:     if (B->factortype == MAT_FACTOR_NONE) {
2975:       Mat_SeqAIJHIPSPARSE *spptr;
2976:       PetscCall(PetscNew(&spptr));
2977:       spptr->format  = MAT_HIPSPARSE_CSR;
2978:       spptr->spmvAlg = HIPSPARSE_SPMV_ALG_DEFAULT;
2979:       spptr->spmmAlg = HIPSPARSE_SPMM_CSR_ALG1; /* default, only support column-major dense matrix B */
2980:       //spptr->csr2cscAlg = HIPSPARSE_CSR2CSC_ALG1;

2982:       B->spptr = spptr;
2983:     } else {
2984:       Mat_SeqAIJHIPSPARSETriFactors *spptr;

2986:       PetscCall(PetscNew(&spptr));
2987:       B->spptr = spptr;
2988:     }
2989:     B->offloadmask = PETSC_OFFLOAD_UNALLOCATED;
2990:   }
2991:   B->ops->assemblyend       = MatAssemblyEnd_SeqAIJHIPSPARSE;
2992:   B->ops->destroy           = MatDestroy_SeqAIJHIPSPARSE;
2993:   B->ops->setoption         = MatSetOption_SeqAIJHIPSPARSE;
2994:   B->ops->setfromoptions    = MatSetFromOptions_SeqAIJHIPSPARSE;
2995:   B->ops->bindtocpu         = MatBindToCPU_SeqAIJHIPSPARSE;
2996:   B->ops->duplicate         = MatDuplicate_SeqAIJHIPSPARSE;
2997:   B->ops->getcurrentmemtype = MatGetCurrentMemType_SeqAIJHIPSPARSE;

2999:   PetscCall(MatBindToCPU_SeqAIJHIPSPARSE(B, PETSC_FALSE));
3000:   PetscCall(PetscObjectChangeTypeName((PetscObject)B, MATSEQAIJHIPSPARSE));
3001:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatHIPSPARSESetFormat_C", MatHIPSPARSESetFormat_SeqAIJHIPSPARSE));
3002: #if PetscDefined(HAVE_HYPRE)
3003:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatConvert_seqaijhipsparse_hypre_C", MatConvert_AIJ_HYPRE));
3004: #endif
3005:   PetscCall(PetscObjectComposeFunction((PetscObject)B, "MatHIPSPARSESetUseCPUSolve_C", MatHIPSPARSESetUseCPUSolve_SeqAIJHIPSPARSE));
3006:   PetscFunctionReturn(PETSC_SUCCESS);
3007: }

3009: PETSC_EXTERN PetscErrorCode MatCreate_SeqAIJHIPSPARSE(Mat B)
3010: {
3011:   PetscFunctionBegin;
3012:   PetscCall(MatCreate_SeqAIJ(B));
3013:   PetscCall(MatConvert_SeqAIJ_SeqAIJHIPSPARSE(B, MATSEQAIJHIPSPARSE, MAT_INPLACE_MATRIX, &B));
3014:   PetscFunctionReturn(PETSC_SUCCESS);
3015: }

3017: /*MC
3018:   MATSEQAIJHIPSPARSE - MATAIJHIPSPARSE = "(seq)aijhipsparse" - A matrix type to be used for sparse matrices on AMD GPUs

3020:   A matrix type whose data resides on AMD GPUs. These matrices can be in either CSR, ELL, or Hybrid format.
3021:   All matrix calculations are performed on AMD/NVIDIA GPUs using the HIPSPARSE library.

3023:   Options Database Keys:
3024: + -mat_type aijhipsparse                           - sets the matrix type to `MATSEQAIJHIPSPARSE`
3025: . -mat_hipsparse_storage_format (csr|ell|hyb)      - sets the storage format of matrices (for `MatMult()` and factors in `MatSolve()`).
3026: . -mat_hipsparse_mult_storage_format (csr|ell|hyb) - sets the storage format of matrices (for `MatMult()`)
3027: - -mat_hipsparse_use_cpu_solve (true|false)        - do `MatSolve()` on the CPU

3029:   Level: beginner

3031: .seealso: [](ch_matrices), `Mat`, `MatCreateSeqAIJHIPSPARSE()`, `MATAIJHIPSPARSE`, `MatCreateAIJHIPSPARSE()`, `MatHIPSPARSESetFormat()`, `MatHIPSPARSEStorageFormat`, `MatHIPSPARSEFormatOperation`
3032: M*/

3034: PETSC_INTERN PetscErrorCode MatSolverTypeRegister_HIPSPARSE(void)
3035: {
3036:   PetscFunctionBegin;
3037:   PetscCall(MatSolverTypeRegister(MATSOLVERHIPSPARSE, MATSEQAIJHIPSPARSE, MAT_FACTOR_LU, MatGetFactor_seqaijhipsparse_hipsparse));
3038:   PetscCall(MatSolverTypeRegister(MATSOLVERHIPSPARSE, MATSEQAIJHIPSPARSE, MAT_FACTOR_CHOLESKY, MatGetFactor_seqaijhipsparse_hipsparse));
3039:   PetscCall(MatSolverTypeRegister(MATSOLVERHIPSPARSE, MATSEQAIJHIPSPARSE, MAT_FACTOR_ILU, MatGetFactor_seqaijhipsparse_hipsparse));
3040:   PetscCall(MatSolverTypeRegister(MATSOLVERHIPSPARSE, MATSEQAIJHIPSPARSE, MAT_FACTOR_ICC, MatGetFactor_seqaijhipsparse_hipsparse));
3041:   PetscFunctionReturn(PETSC_SUCCESS);
3042: }

3044: static PetscErrorCode MatSeqAIJHIPSPARSE_Destroy(Mat mat)
3045: {
3046:   Mat_SeqAIJHIPSPARSE *cusp = static_cast<Mat_SeqAIJHIPSPARSE *>(mat->spptr);

3048:   PetscFunctionBegin;
3049:   if (cusp) {
3050:     PetscCall(MatSeqAIJHIPSPARSEMultStruct_Destroy(&cusp->mat, cusp->format));
3051:     PetscCall(MatSeqAIJHIPSPARSEMultStruct_Destroy(&cusp->matTranspose, cusp->format));
3052:     delete cusp->workVector;
3053:     delete cusp->rowoffsets_gpu;
3054:     delete cusp->csr2csc_i;
3055:     delete cusp->coords;
3056:     PetscCall(PetscFree(mat->spptr));
3057:   }
3058:   PetscFunctionReturn(PETSC_SUCCESS);
3059: }

3061: static PetscErrorCode CsrMatrix_Destroy(CsrMatrix **mat)
3062: {
3063:   PetscFunctionBegin;
3064:   if (*mat) {
3065:     delete (*mat)->values;
3066:     delete (*mat)->column_indices;
3067:     delete (*mat)->row_offsets;
3068:     delete *mat;
3069:     *mat = 0;
3070:   }
3071:   PetscFunctionReturn(PETSC_SUCCESS);
3072: }

3074: static PetscErrorCode MatSeqAIJHIPSPARSEMultStruct_Destroy(Mat_SeqAIJHIPSPARSEMultStruct **matstruct, MatHIPSPARSEStorageFormat format)
3075: {
3076:   CsrMatrix *mat;

3078:   PetscFunctionBegin;
3079:   if (*matstruct) {
3080:     if ((*matstruct)->mat) {
3081: #if !defined(CUDART_VERSION) || CUDART_VERSION < 11000
3082:       if (format == MAT_HIPSPARSE_ELL || format == MAT_HIPSPARSE_HYB) {
3083:         hipsparseHybMat_t hybMat = (hipsparseHybMat_t)(*matstruct)->mat;
3084:         PetscCallHIPSPARSE(hipsparseDestroyHybMat(hybMat));
3085:       } else
3086: #endif
3087:       {
3088:         mat = (CsrMatrix *)(*matstruct)->mat;
3089:         PetscCall(CsrMatrix_Destroy(&mat));
3090:       }
3091:     }
3092:     if ((*matstruct)->descr) PetscCallHIPSPARSE(hipsparseDestroyMatDescr((*matstruct)->descr));
3093:     delete (*matstruct)->cprowIndices;
3094:     PetscCallHIP(hipFree((*matstruct)->alpha_one));
3095:     PetscCallHIP(hipFree((*matstruct)->beta_zero));
3096:     PetscCallHIP(hipFree((*matstruct)->beta_one));

3098:     Mat_SeqAIJHIPSPARSEMultStruct *mdata = *matstruct;
3099:     if (mdata->matDescr) PetscCallHIPSPARSE(hipsparseDestroySpMat(mdata->matDescr));
3100:     for (int i = 0; i < 3; i++) {
3101:       if (mdata->hipSpMV[i].initialized) {
3102:         PetscCallHIP(hipFree(mdata->hipSpMV[i].spmvBuffer));
3103:         PetscCallHIPSPARSE(hipsparseDestroyDnVec(mdata->hipSpMV[i].vecXDescr));
3104:         PetscCallHIPSPARSE(hipsparseDestroyDnVec(mdata->hipSpMV[i].vecYDescr));
3105:         PetscCallHIPSPARSE(hipsparseDestroySpMat(mdata->hipSpMV[i].matDescr));
3106:       }
3107:       if (mdata->matDescr_SpMM[i]) PetscCallHIPSPARSE(hipsparseDestroySpMat(mdata->matDescr_SpMM[i]));
3108:     }
3109:     delete *matstruct;
3110:     *matstruct = NULL;
3111:   }
3112:   PetscFunctionReturn(PETSC_SUCCESS);
3113: }

3115: PetscErrorCode MatSeqAIJHIPSPARSETriFactors_Reset(Mat_SeqAIJHIPSPARSETriFactors_p *trifactors)
3116: {
3117:   Mat_SeqAIJHIPSPARSETriFactors *fs = *trifactors;

3119:   PetscFunctionBegin;
3120:   if (fs) {
3121:     delete fs->rpermIndices;
3122:     delete fs->cpermIndices;
3123:     fs->rpermIndices  = NULL;
3124:     fs->cpermIndices  = NULL;
3125:     fs->init_dev_prop = PETSC_FALSE;
3126:     PetscCallHIP(hipFree(fs->csrRowPtr));
3127:     PetscCallHIP(hipFree(fs->csrColIdx));
3128:     PetscCallHIP(hipFree(fs->csrRowPtr32));
3129:     PetscCallHIP(hipFree(fs->csrColIdx32));
3130:     PetscCallHIP(hipFree(fs->csrVal));
3131:     PetscCallHIP(hipFree(fs->diag));
3132:     PetscCallHIP(hipFree(fs->X));
3133:     PetscCallHIP(hipFree(fs->Y));
3134:     // PetscCallHIP(hipFree(fs->factBuffer_M)); /* No needed since factBuffer_M shares with one of spsvBuffer_L/U */
3135:     PetscCallHIP(hipFree(fs->spsvBuffer_L));
3136:     PetscCallHIP(hipFree(fs->spsvBuffer_U));
3137:     PetscCallHIP(hipFree(fs->spsvBuffer_Lt));
3138:     PetscCallHIP(hipFree(fs->spsvBuffer_Ut));
3139:     PetscCallHIPSPARSE(hipsparseDestroyMatDescr(fs->matDescr_M));
3140:     if (fs->spMatDescr_L) PetscCallHIPSPARSE(hipsparseDestroySpMat(fs->spMatDescr_L));
3141:     if (fs->spMatDescr_U) PetscCallHIPSPARSE(hipsparseDestroySpMat(fs->spMatDescr_U));
3142:     if (fs->spMatDescr_Lt) PetscCallHIPSPARSE(hipsparseDestroySpMat(fs->spMatDescr_Lt));
3143:     if (fs->spMatDescr_Ut) PetscCallHIPSPARSE(hipsparseDestroySpMat(fs->spMatDescr_Ut));
3144:     fs->spMatDescr_Lt = fs->spMatDescr_Ut = NULL;
3145:     PetscCallHIPSPARSE(hipsparseSpSV_destroyDescr(fs->spsvDescr_L));
3146:     PetscCallHIPSPARSE(hipsparseSpSV_destroyDescr(fs->spsvDescr_Lt));
3147:     PetscCallHIPSPARSE(hipsparseSpSV_destroyDescr(fs->spsvDescr_U));
3148:     PetscCallHIPSPARSE(hipsparseSpSV_destroyDescr(fs->spsvDescr_Ut));
3149:     if (fs->dnVecDescr_X) PetscCallHIPSPARSE(hipsparseDestroyDnVec(fs->dnVecDescr_X));
3150:     if (fs->dnVecDescr_Y) PetscCallHIPSPARSE(hipsparseDestroyDnVec(fs->dnVecDescr_Y));
3151:     PetscCallHIPSPARSE(hipsparseDestroyCsrilu02Info(fs->ilu0Info_M));
3152:     PetscCallHIPSPARSE(hipsparseDestroyCsric02Info(fs->ic0Info_M));
3153:     PetscCall(PetscFree(fs->csrRowPtr_h));
3154:     PetscCall(PetscFree(fs->csrVal_h));
3155:     PetscCall(PetscFree(fs->diag_h));
3156:     fs->createdTransposeSpSVDescr    = PETSC_FALSE;
3157:     fs->updatedTransposeSpSVAnalysis = PETSC_FALSE;
3158:   }
3159:   PetscFunctionReturn(PETSC_SUCCESS);
3160: }

3162: static PetscErrorCode MatSeqAIJHIPSPARSETriFactors_Destroy(Mat_SeqAIJHIPSPARSETriFactors **trifactors)
3163: {
3164:   PetscFunctionBegin;
3165:   if (*trifactors) {
3166:     PetscCall(MatSeqAIJHIPSPARSETriFactors_Reset(trifactors));
3167:     PetscCall(PetscFree(*trifactors));
3168:   }
3169:   PetscFunctionReturn(PETSC_SUCCESS);
3170: }

3172: static PetscErrorCode MatSeqAIJHIPSPARSEInvalidateTranspose(Mat A, PetscBool destroy)
3173: {
3174:   Mat_SeqAIJHIPSPARSE *cusp = (Mat_SeqAIJHIPSPARSE *)A->spptr;

3176:   PetscFunctionBegin;
3177:   PetscCheckTypeName(A, MATSEQAIJHIPSPARSE);
3178:   if (!cusp) PetscFunctionReturn(PETSC_SUCCESS);
3179:   if (destroy) {
3180:     PetscCall(MatSeqAIJHIPSPARSEMultStruct_Destroy(&cusp->matTranspose, cusp->format));
3181:     delete cusp->csr2csc_i;
3182:     cusp->csr2csc_i = NULL;
3183:   }
3184:   A->transupdated = PETSC_FALSE;
3185:   PetscFunctionReturn(PETSC_SUCCESS);
3186: }

3188: static PetscErrorCode MatSetPreallocationCOO_SeqAIJHIPSPARSE(Mat mat, PetscCount coo_n, PetscInt coo_i[], PetscInt coo_j[])
3189: {
3190:   PetscFunctionBegin;
3191:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::SetPreallocationCOO(mat, coo_n, coo_i, coo_j));
3192:   PetscFunctionReturn(PETSC_SUCCESS);
3193: }

3195: static PetscErrorCode MatSetValuesCOO_SeqAIJHIPSPARSE(Mat A, const PetscScalar v[], InsertMode imode)
3196: {
3197:   PetscFunctionBegin;
3198:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::SetValuesCOO(A, v, imode));
3199:   PetscFunctionReturn(PETSC_SUCCESS);
3200: }

3202: /*@
3203:   MatSeqAIJHIPSPARSEGetIJ - returns the device row storage `i` and `j` indices for `MATSEQAIJHIPSPARSE` matrices.

3205:   Not Collective

3207:   Input Parameters:
3208: + A          - the matrix
3209: - compressed - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be always returned in compressed form

3211:   Output Parameters:
3212: + i - the CSR row pointers
3213: - j - the CSR column indices

3215:   Level: developer

3217:   Note:
3218:   When compressed is true, the CSR structure does not contain empty rows

3220: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJHIPSPARSERestoreIJ()`, `MatSeqAIJHIPSPARSEGetArrayRead()`
3221: @*/
3222: PetscErrorCode MatSeqAIJHIPSPARSEGetIJ(Mat A, PetscBool compressed, const PetscInt *i[], const PetscInt *j[])
3223: {
3224:   PetscFunctionBegin;
3225:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetIJ(A, compressed, i, j));
3226:   PetscFunctionReturn(PETSC_SUCCESS);
3227: }

3229: /*@
3230:   MatSeqAIJHIPSPARSERestoreIJ - restore the device row storage `i` and `j` indices obtained with `MatSeqAIJHIPSPARSEGetIJ()`

3232:   Not Collective

3234:   Input Parameters:
3235: + A          - the matrix
3236: . compressed - `PETSC_TRUE` or `PETSC_FALSE` indicating the matrix data structure should be always returned in compressed form
3237: . i          - the CSR row pointers
3238: - j          - the CSR column indices

3240:   Level: developer

3242: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJHIPSPARSEGetIJ()`
3243: @*/
3244: PetscErrorCode MatSeqAIJHIPSPARSERestoreIJ(Mat A, PetscBool compressed, const PetscInt *i[], const PetscInt *j[])
3245: {
3246:   PetscFunctionBegin;
3247:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::RestoreIJ(A, compressed, i, j));
3248:   PetscFunctionReturn(PETSC_SUCCESS);
3249: }

3251: /*@
3252:   MatSeqAIJHIPSPARSEGetArrayRead - gives read-only access to the array where the device data for a `MATSEQAIJHIPSPARSE` matrix is stored

3254:   Not Collective

3256:   Input Parameter:
3257: . A - a `MATSEQAIJHIPSPARSE` matrix

3259:   Output Parameter:
3260: . a - pointer to the device data

3262:   Level: developer

3264:   Note:
3265:   May trigger host-device copies if the up-to-date matrix data is on host

3267: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJHIPSPARSEGetArray()`, `MatSeqAIJHIPSPARSEGetArrayWrite()`, `MatSeqAIJHIPSPARSERestoreArrayRead()`
3268: @*/
3269: PetscErrorCode MatSeqAIJHIPSPARSEGetArrayRead(Mat A, const PetscScalar *a[])
3270: {
3271:   return MatSeqAIJHIPSPARSE_CUPM_t::GetArrayRead(A, a);
3272: }

3274: /*@
3275:   MatSeqAIJHIPSPARSERestoreArrayRead - restore the read-only access array obtained from `MatSeqAIJHIPSPARSEGetArrayRead()`

3277:   Not Collective

3279:   Input Parameters:
3280: + A - a `MATSEQAIJHIPSPARSE` matrix
3281: - a - pointer to the device data

3283:   Level: developer

3285: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJHIPSPARSEGetArrayRead()`
3286: @*/
3287: PetscErrorCode MatSeqAIJHIPSPARSERestoreArrayRead(Mat A, const PetscScalar *a[])
3288: {
3289:   return MatSeqAIJHIPSPARSE_CUPM_t::RestoreArrayRead(A, a);
3290: }

3292: /*@
3293:   MatSeqAIJHIPSPARSEGetArray - gives read-write access to the array where the device data for a `MATSEQAIJHIPSPARSE` matrix is stored

3295:   Not Collective

3297:   Input Parameter:
3298: . A - a `MATSEQAIJHIPSPARSE` matrix

3300:   Output Parameter:
3301: . a - pointer to the device data

3303:   Level: developer

3305:   Note:
3306:   May trigger host-device copies if up-to-date matrix data is on host

3308: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJHIPSPARSEGetArrayRead()`, `MatSeqAIJHIPSPARSEGetArrayWrite()`, `MatSeqAIJHIPSPARSERestoreArray()`
3309: @*/
3310: PetscErrorCode MatSeqAIJHIPSPARSEGetArray(Mat A, PetscScalar *a[])
3311: {
3312:   return MatSeqAIJHIPSPARSE_CUPM_t::GetArray(A, a);
3313: }
3314: /*@
3315:   MatSeqAIJHIPSPARSERestoreArray - restore the read-write access array obtained from `MatSeqAIJHIPSPARSEGetArray()`

3317:   Not Collective

3319:   Input Parameters:
3320: + A - a `MATSEQAIJHIPSPARSE` matrix
3321: - a - pointer to the device data

3323:   Level: developer

3325: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJHIPSPARSEGetArray()`
3326: @*/
3327: PetscErrorCode MatSeqAIJHIPSPARSERestoreArray(Mat A, PetscScalar *a[])
3328: {
3329:   return MatSeqAIJHIPSPARSE_CUPM_t::RestoreArray(A, a);
3330: }

3332: /*@
3333:   MatSeqAIJHIPSPARSEGetArrayWrite - gives write access to the array where the device data for a `MATSEQAIJHIPSPARSE` matrix is stored

3335:   Not Collective

3337:   Input Parameter:
3338: . A - a `MATSEQAIJHIPSPARSE` matrix

3340:   Output Parameter:
3341: . a - pointer to the device data

3343:   Level: developer

3345:   Note:
3346:   Does not trigger host-device copies and flags data validity on the GPU

3348: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJHIPSPARSEGetArray()`, `MatSeqAIJHIPSPARSEGetArrayRead()`, `MatSeqAIJHIPSPARSERestoreArrayWrite()`
3349: @*/
3350: PetscErrorCode MatSeqAIJHIPSPARSEGetArrayWrite(Mat A, PetscScalar *a[])
3351: {
3352:   return MatSeqAIJHIPSPARSE_CUPM_t::GetArrayWrite(A, a);
3353: }

3355: /*@
3356:   MatSeqAIJHIPSPARSERestoreArrayWrite - restore the write-only access array obtained from `MatSeqAIJHIPSPARSEGetArrayWrite()`

3358:   Not Collective

3360:   Input Parameters:
3361: + A - a `MATSEQAIJHIPSPARSE` matrix
3362: - a - pointer to the device data

3364:   Level: developer

3366: .seealso: [](ch_matrices), `Mat`, `MatSeqAIJHIPSPARSEGetArrayWrite()`
3367: @*/
3368: PetscErrorCode MatSeqAIJHIPSPARSERestoreArrayWrite(Mat A, PetscScalar *a[])
3369: {
3370:   return MatSeqAIJHIPSPARSE_CUPM_t::RestoreArrayWrite(A, a);
3371: }

3373: struct IJCompare4 {
3374:   __host__ __device__ inline bool operator()(const thrust::tuple<int, int, PetscScalar, int> &t1, const thrust::tuple<int, int, PetscScalar, int> &t2)
3375:   {
3376:     if (thrust::get<0>(t1) < thrust::get<0>(t2)) return true;
3377:     if (thrust::get<0>(t1) == thrust::get<0>(t2)) return thrust::get<1>(t1) < thrust::get<1>(t2);
3378:     return false;
3379:   }
3380: };

3382: struct Shift {
3383:   int _shift;

3385:   Shift(int shift) : _shift(shift) { }
3386:   __host__ __device__ inline int operator()(const int &c) { return c + _shift; }
3387: };

3389: /* merges two SeqAIJHIPSPARSE matrices A, B by concatenating their rows. [A';B']' operation in MATLAB notation */
3390: PetscErrorCode MatSeqAIJHIPSPARSEMergeMats(Mat A, Mat B, MatReuse reuse, Mat *C)
3391: {
3392:   Mat_SeqAIJ                    *a = (Mat_SeqAIJ *)A->data, *b = (Mat_SeqAIJ *)B->data, *c;
3393:   Mat_SeqAIJHIPSPARSE           *Acusp = (Mat_SeqAIJHIPSPARSE *)A->spptr, *Bcusp = (Mat_SeqAIJHIPSPARSE *)B->spptr, *Ccusp;
3394:   Mat_SeqAIJHIPSPARSEMultStruct *Cmat;
3395:   CsrMatrix                     *Acsr, *Bcsr, *Ccsr;
3396:   PetscInt                       Annz, Bnnz;
3397:   PetscInt                       i, m, n, zero = 0;
3398:   PetscDeviceContext             dctx;
3399:   hipStream_t                    stream;

3401:   PetscFunctionBegin;
3404:   PetscAssertPointer(C, 4);
3405:   PetscCheckTypeName(A, MATSEQAIJHIPSPARSE);
3406:   PetscCheckTypeName(B, MATSEQAIJHIPSPARSE);
3407:   PetscCheck(A->rmap->n == B->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Invalid number or rows %" PetscInt_FMT " != %" PetscInt_FMT, A->rmap->n, B->rmap->n);
3408:   PetscCheck(reuse != MAT_INPLACE_MATRIX, PETSC_COMM_SELF, PETSC_ERR_SUP, "MAT_INPLACE_MATRIX not supported");
3409:   PetscCheck(Acusp->format != MAT_HIPSPARSE_ELL && Acusp->format != MAT_HIPSPARSE_HYB, PETSC_COMM_SELF, PETSC_ERR_SUP, "Not implemented");
3410:   PetscCheck(Bcusp->format != MAT_HIPSPARSE_ELL && Bcusp->format != MAT_HIPSPARSE_HYB, PETSC_COMM_SELF, PETSC_ERR_SUP, "Not implemented");
3411:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::GetHandles_(&dctx, &stream));
3412:   if (reuse == MAT_INITIAL_MATRIX) {
3413:     m = A->rmap->n;
3414:     n = A->cmap->n + B->cmap->n;
3415:     PetscCall(MatCreate(PETSC_COMM_SELF, C));
3416:     PetscCall(MatSetSizes(*C, m, n, m, n));
3417:     PetscCall(MatSetType(*C, MATSEQAIJHIPSPARSE));
3418:     c                       = (Mat_SeqAIJ *)(*C)->data;
3419:     Ccusp                   = (Mat_SeqAIJHIPSPARSE *)(*C)->spptr;
3420:     Cmat                    = new Mat_SeqAIJHIPSPARSEMultStruct;
3421:     Ccsr                    = new CsrMatrix;
3422:     Cmat->cprowIndices      = NULL;
3423:     c->compressedrow.use    = PETSC_FALSE;
3424:     c->compressedrow.nrows  = 0;
3425:     c->compressedrow.i      = NULL;
3426:     c->compressedrow.rindex = NULL;
3427:     Ccusp->workVector       = NULL;
3428:     Ccusp->nrows            = m;
3429:     Ccusp->mat              = Cmat;
3430:     Ccusp->mat->mat         = Ccsr;
3431:     Ccsr->num_rows          = m;
3432:     Ccsr->num_cols          = n;
3433:     PetscCallHIPSPARSE(hipsparseCreateMatDescr(&Cmat->descr));
3434:     PetscCallHIPSPARSE(hipsparseSetMatIndexBase(Cmat->descr, HIPSPARSE_INDEX_BASE_ZERO));
3435:     PetscCallHIPSPARSE(hipsparseSetMatType(Cmat->descr, HIPSPARSE_MATRIX_TYPE_GENERAL));
3436:     PetscCallHIP(hipMalloc((void **)&Cmat->alpha_one, sizeof(PetscScalar)));
3437:     PetscCallHIP(hipMalloc((void **)&Cmat->beta_zero, sizeof(PetscScalar)));
3438:     PetscCallHIP(hipMalloc((void **)&Cmat->beta_one, sizeof(PetscScalar)));
3439:     PetscCallHIP(hipMemcpyAsync(Cmat->alpha_one, &PETSC_HIPSPARSE_ONE, sizeof(PetscScalar), hipMemcpyHostToDevice, stream));
3440:     PetscCallHIP(hipMemcpyAsync(Cmat->beta_zero, &PETSC_HIPSPARSE_ZERO, sizeof(PetscScalar), hipMemcpyHostToDevice, stream));
3441:     PetscCallHIP(hipMemcpyAsync(Cmat->beta_one, &PETSC_HIPSPARSE_ONE, sizeof(PetscScalar), hipMemcpyHostToDevice, stream));
3442:     PetscCall(MatSeqAIJHIPSPARSECopyToGPU(A));
3443:     PetscCall(MatSeqAIJHIPSPARSECopyToGPU(B));
3444:     PetscCheck(Acusp->mat, PETSC_COMM_SELF, PETSC_ERR_COR, "Missing Mat_SeqAIJHIPSPARSEMultStruct");
3445:     PetscCheck(Bcusp->mat, PETSC_COMM_SELF, PETSC_ERR_COR, "Missing Mat_SeqAIJHIPSPARSEMultStruct");

3447:     Acsr                 = (CsrMatrix *)Acusp->mat->mat;
3448:     Bcsr                 = (CsrMatrix *)Bcusp->mat->mat;
3449:     Annz                 = (PetscInt)Acsr->column_indices->size();
3450:     Bnnz                 = (PetscInt)Bcsr->column_indices->size();
3451:     c->nz                = Annz + Bnnz;
3452:     Ccsr->row_offsets    = new THRUSTINTARRAY(m + 1);
3453:     Ccsr->column_indices = new THRUSTINTARRAY(c->nz);
3454:     Ccsr->values         = new THRUSTARRAY(c->nz);
3455:     Ccsr->num_entries    = c->nz;
3456:     Ccusp->coords        = new THRUSTINTARRAY(c->nz);
3457:     if (c->nz) {
3458:       auto            Acoo = new THRUSTINTARRAY(Annz); // initialized with zeros
3459:       auto            Bcoo = new THRUSTINTARRAY(Bnnz);
3460:       auto            Ccoo = new THRUSTINTARRAY(c->nz);
3461:       THRUSTINTARRAY *Aroff, *Broff;

3463:       if (a->compressedrow.use) { /* need full row offset */
3464:         if (!Acusp->rowoffsets_gpu) {
3465:           Acusp->rowoffsets_gpu = new THRUSTINTARRAY(A->rmap->n + 1);
3466:           PetscCallHIP(hipMemcpyAsync(Acusp->rowoffsets_gpu->data().get(), a->i, (A->rmap->n + 1) * sizeof(*a->i), hipMemcpyHostToDevice, stream));
3467:           PetscCall(PetscLogCpuToGpu((A->rmap->n + 1) * sizeof(PetscInt)));
3468:         }
3469:         Aroff = Acusp->rowoffsets_gpu;
3470:       } else Aroff = Acsr->row_offsets;
3471:       if (b->compressedrow.use) { /* need full row offset */
3472:         if (!Bcusp->rowoffsets_gpu) {
3473:           Bcusp->rowoffsets_gpu = new THRUSTINTARRAY(B->rmap->n + 1);
3474:           PetscCallHIP(hipMemcpyAsync(Bcusp->rowoffsets_gpu->data().get(), b->i, (B->rmap->n + 1) * sizeof(*b->i), hipMemcpyHostToDevice, stream));
3475:           PetscCall(PetscLogCpuToGpu((B->rmap->n + 1) * sizeof(PetscInt)));
3476:         }
3477:         Broff = Bcusp->rowoffsets_gpu;
3478:       } else Broff = Bcsr->row_offsets;
3479:       PetscCall(PetscLogGpuTimeBegin());
3480:       // Implement cusparseXcsr2coo() with Thrust, as the former doesn't support 64-bit indices.
3481:       PetscCallThrust(thrust::for_each(thrust::device.on(stream), thrust::counting_iterator<PetscInt>(0), thrust::counting_iterator<PetscInt>(m), Csr2coo(Aroff->data().get(), Acoo->data().get())));
3482:       PetscCallThrust(thrust::for_each(thrust::device.on(stream), thrust::counting_iterator<PetscInt>(0), thrust::counting_iterator<PetscInt>(m), Csr2coo(Broff->data().get(), Bcoo->data().get())));

3484:       /* Issues when using bool with large matrices on SUMMIT 10.2.89 */
3485:       auto Aperm = thrust::make_constant_iterator(1);
3486:       auto Bperm = thrust::make_constant_iterator(0);
3487:       auto Bcib  = thrust::make_transform_iterator(Bcsr->column_indices->begin(), Shift(A->cmap->n));
3488:       auto Bcie  = thrust::make_transform_iterator(Bcsr->column_indices->end(), Shift(A->cmap->n));
3489:       auto wPerm = new THRUSTINTARRAY(Annz + Bnnz);
3490:       auto Azb   = thrust::make_zip_iterator(thrust::make_tuple(Acoo->begin(), Acsr->column_indices->begin(), Acsr->values->begin(), Aperm));
3491:       auto Aze   = thrust::make_zip_iterator(thrust::make_tuple(Acoo->end(), Acsr->column_indices->end(), Acsr->values->end(), Aperm));
3492:       auto Bzb   = thrust::make_zip_iterator(thrust::make_tuple(Bcoo->begin(), Bcib, Bcsr->values->begin(), Bperm)); // Use B column indices shifted by A->cmap->n
3493:       auto Bze   = thrust::make_zip_iterator(thrust::make_tuple(Bcoo->end(), Bcie, Bcsr->values->end(), Bperm));
3494:       auto Czb   = thrust::make_zip_iterator(thrust::make_tuple(Ccoo->begin(), Ccsr->column_indices->begin(), Ccsr->values->begin(), wPerm->begin()));
3495:       auto p1    = Ccusp->coords->begin();
3496:       auto p2    = Ccusp->coords->begin();
3497:       thrust::advance(p2, Annz);
3498:       PetscCallThrust(thrust::merge(thrust::device.on(stream), Azb, Aze, Bzb, Bze, Czb, IJCompare4())); // put nonzeros in A and B to C in sorted order (by row and then by column)
3499:       auto cci = thrust::make_counting_iterator(zero);
3500:       auto cce = thrust::make_counting_iterator(c->nz);
3501: #if THRUST_VERSION < 200800
3502:       auto pred = thrust::identity<int>();
3503: #else
3504:       auto pred = ::internal::identity();
3505: #endif
3506:       PetscCallThrust(thrust::copy_if(thrust::device.on(stream), cci, cce, wPerm->begin(), p1, pred));
3507:       PetscCallThrust(thrust::remove_copy_if(thrust::device.on(stream), cci, cce, wPerm->begin(), p2, pred));
3508:       // Implement a simplified hipsparseXcoo2csr() with Thrust (assuming the row indices are already sorted), as the former doesn't support 64-bit indices.
3509:       PetscCallThrust(thrust::lower_bound(thrust::device.on(stream), Ccoo->begin(), Ccoo->end(), thrust::counting_iterator<PetscInt>(0), thrust::counting_iterator<PetscInt>(m + 1), Ccsr->row_offsets->begin()));
3510:       PetscCall(PetscLogGpuTimeEnd());
3511:       delete wPerm;
3512:       delete Acoo;
3513:       delete Bcoo;
3514:       delete Ccoo;
3515:       PetscCallHIPSPARSE(hipsparseCreateCsr(&Cmat->matDescr, Ccsr->num_rows, Ccsr->num_cols, Ccsr->num_entries, Ccsr->row_offsets->data().get(), Ccsr->column_indices->data().get(), Ccsr->values->data().get(), csrRowOffsetsType, csrColIndType, HIPSPARSE_INDEX_BASE_ZERO, hipsparse_scalartype));
3516:       if (A->form_explicit_transpose && B->form_explicit_transpose) { /* if A and B have the transpose, generate C transpose too */
3517:         PetscCall(MatSeqAIJHIPSPARSEFormExplicitTranspose(A));
3518:         PetscCall(MatSeqAIJHIPSPARSEFormExplicitTranspose(B));
3519:         PetscBool                      AT = Acusp->matTranspose ? PETSC_TRUE : PETSC_FALSE, BT = Bcusp->matTranspose ? PETSC_TRUE : PETSC_FALSE;
3520:         Mat_SeqAIJHIPSPARSEMultStruct *CmatT = new Mat_SeqAIJHIPSPARSEMultStruct;
3521:         CsrMatrix                     *CcsrT = new CsrMatrix;
3522:         CsrMatrix                     *AcsrT = AT ? (CsrMatrix *)Acusp->matTranspose->mat : NULL;
3523:         CsrMatrix                     *BcsrT = BT ? (CsrMatrix *)Bcusp->matTranspose->mat : NULL;

3525:         (*C)->form_explicit_transpose = PETSC_TRUE;
3526:         (*C)->transupdated            = PETSC_TRUE;
3527:         Ccusp->rowoffsets_gpu         = NULL;
3528:         CmatT->cprowIndices           = NULL;
3529:         CmatT->mat                    = CcsrT;
3530:         CcsrT->num_rows               = n;
3531:         CcsrT->num_cols               = m;
3532:         CcsrT->num_entries            = c->nz;

3534:         CcsrT->row_offsets    = new THRUSTINTARRAY(n + 1);
3535:         CcsrT->column_indices = new THRUSTINTARRAY(c->nz);
3536:         CcsrT->values         = new THRUSTARRAY(c->nz);

3538:         PetscCall(PetscLogGpuTimeBegin());
3539:         auto rT = CcsrT->row_offsets->begin();
3540:         if (AT) {
3541:           PetscCallThrust(rT = thrust::copy(thrust::device.on(stream), AcsrT->row_offsets->begin(), AcsrT->row_offsets->end(), rT));
3542:           thrust::advance(rT, -1);
3543:         }
3544:         if (BT) {
3545:           auto titb = thrust::make_transform_iterator(BcsrT->row_offsets->begin(), Shift(a->nz));
3546:           auto tite = thrust::make_transform_iterator(BcsrT->row_offsets->end(), Shift(a->nz));
3547:           PetscCallThrust(thrust::copy(thrust::device.on(stream), titb, tite, rT));
3548:         }
3549:         auto cT = CcsrT->column_indices->begin();
3550:         if (AT) PetscCallThrust(cT = thrust::copy(thrust::device.on(stream), AcsrT->column_indices->begin(), AcsrT->column_indices->end(), cT));
3551:         if (BT) PetscCallThrust(thrust::copy(thrust::device.on(stream), BcsrT->column_indices->begin(), BcsrT->column_indices->end(), cT));
3552:         auto vT = CcsrT->values->begin();
3553:         if (AT) PetscCallThrust(vT = thrust::copy(thrust::device.on(stream), AcsrT->values->begin(), AcsrT->values->end(), vT));
3554:         if (BT) PetscCallThrust(thrust::copy(thrust::device.on(stream), BcsrT->values->begin(), BcsrT->values->end(), vT));
3555:         PetscCall(PetscLogGpuTimeEnd());

3557:         PetscCallHIPSPARSE(hipsparseCreateMatDescr(&CmatT->descr));
3558:         PetscCallHIPSPARSE(hipsparseSetMatIndexBase(CmatT->descr, HIPSPARSE_INDEX_BASE_ZERO));
3559:         PetscCallHIPSPARSE(hipsparseSetMatType(CmatT->descr, HIPSPARSE_MATRIX_TYPE_GENERAL));
3560:         PetscCallHIP(hipMalloc((void **)&CmatT->alpha_one, sizeof(PetscScalar)));
3561:         PetscCallHIP(hipMalloc((void **)&CmatT->beta_zero, sizeof(PetscScalar)));
3562:         PetscCallHIP(hipMalloc((void **)&CmatT->beta_one, sizeof(PetscScalar)));
3563:         PetscCallHIP(hipMemcpyAsync(CmatT->alpha_one, &PETSC_HIPSPARSE_ONE, sizeof(PetscScalar), hipMemcpyHostToDevice, stream));
3564:         PetscCallHIP(hipMemcpyAsync(CmatT->beta_zero, &PETSC_HIPSPARSE_ZERO, sizeof(PetscScalar), hipMemcpyHostToDevice, stream));
3565:         PetscCallHIP(hipMemcpyAsync(CmatT->beta_one, &PETSC_HIPSPARSE_ONE, sizeof(PetscScalar), hipMemcpyHostToDevice, stream));
3566:         PetscCallHIPSPARSE(hipsparseCreateCsr(&CmatT->matDescr, CcsrT->num_rows, CcsrT->num_cols, CcsrT->num_entries, CcsrT->row_offsets->data().get(), CcsrT->column_indices->data().get(), CcsrT->values->data().get(), csrRowOffsetsType, csrColIndType, HIPSPARSE_INDEX_BASE_ZERO, hipsparse_scalartype));
3567:         Ccusp->matTranspose = CmatT;
3568:       }
3569:     }

3571:     c->free_a = PETSC_TRUE;
3572:     PetscCall(PetscShmgetAllocateArray(c->nz, sizeof(PetscInt), (void **)&c->j));
3573:     PetscCall(PetscShmgetAllocateArray(m + 1, sizeof(PetscInt), (void **)&c->i));
3574:     c->free_ij = PETSC_TRUE;
3575:     PetscCallHIP(hipMemcpyAsync(c->i, Ccsr->row_offsets->data().get(), Ccsr->row_offsets->size() * sizeof(PetscInt), hipMemcpyDeviceToHost, stream));
3576:     PetscCallHIP(hipMemcpyAsync(c->j, Ccsr->column_indices->data().get(), Ccsr->column_indices->size() * sizeof(PetscInt), hipMemcpyDeviceToHost, stream));
3577:     PetscCall(PetscDeviceContextSynchronize(dctx));
3578:     PetscCall(PetscLogGpuToCpu((Ccsr->column_indices->size() + Ccsr->row_offsets->size()) * sizeof(PetscInt)));
3579:     PetscCall(PetscMalloc1(m, &c->ilen));
3580:     PetscCall(PetscMalloc1(m, &c->imax));
3581:     c->maxnz         = c->nz;
3582:     c->nonzerorowcnt = 0;
3583:     c->rmax          = 0;
3584:     for (i = 0; i < m; i++) {
3585:       const PetscInt nn = c->i[i + 1] - c->i[i];
3586:       c->ilen[i] = c->imax[i] = nn;
3587:       c->nonzerorowcnt += (PetscInt)!!nn;
3588:       c->rmax = PetscMax(c->rmax, nn);
3589:     }
3590:     PetscCall(PetscMalloc1(c->nz, &c->a));
3591:     (*C)->nonzerostate++;
3592:     PetscCall(PetscLayoutSetUp((*C)->rmap));
3593:     PetscCall(PetscLayoutSetUp((*C)->cmap));
3594:     Ccusp->nonzerostate = (*C)->nonzerostate;
3595:     (*C)->preallocated  = PETSC_TRUE;
3596:   } else {
3597:     PetscCheck((*C)->rmap->n == B->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Invalid number or rows %" PetscInt_FMT " != %" PetscInt_FMT, (*C)->rmap->n, B->rmap->n);
3598:     c = (Mat_SeqAIJ *)(*C)->data;
3599:     if (c->nz) {
3600:       Ccusp = (Mat_SeqAIJHIPSPARSE *)(*C)->spptr;
3601:       PetscCheck(Ccusp->coords, PETSC_COMM_SELF, PETSC_ERR_COR, "Missing coords");
3602:       PetscCheck(Ccusp->format != MAT_HIPSPARSE_ELL && Ccusp->format != MAT_HIPSPARSE_HYB, PETSC_COMM_SELF, PETSC_ERR_SUP, "Not implemented");
3603:       PetscCheck(Ccusp->nonzerostate == (*C)->nonzerostate, PETSC_COMM_SELF, PETSC_ERR_COR, "Wrong nonzerostate");
3604:       PetscCall(MatSeqAIJHIPSPARSECopyToGPU(A));
3605:       PetscCall(MatSeqAIJHIPSPARSECopyToGPU(B));
3606:       PetscCheck(Acusp->mat, PETSC_COMM_SELF, PETSC_ERR_COR, "Missing Mat_SeqAIJHIPSPARSEMultStruct");
3607:       PetscCheck(Bcusp->mat, PETSC_COMM_SELF, PETSC_ERR_COR, "Missing Mat_SeqAIJHIPSPARSEMultStruct");
3608:       Acsr = (CsrMatrix *)Acusp->mat->mat;
3609:       Bcsr = (CsrMatrix *)Bcusp->mat->mat;
3610:       Ccsr = (CsrMatrix *)Ccusp->mat->mat;
3611:       PetscCheck(Acsr->num_entries == (PetscInt)Acsr->values->size(), PETSC_COMM_SELF, PETSC_ERR_COR, "A nnz %" PetscInt_FMT " != %" PetscInt_FMT, Acsr->num_entries, (PetscInt)Acsr->values->size());
3612:       PetscCheck(Bcsr->num_entries == (PetscInt)Bcsr->values->size(), PETSC_COMM_SELF, PETSC_ERR_COR, "B nnz %" PetscInt_FMT " != %" PetscInt_FMT, Bcsr->num_entries, (PetscInt)Bcsr->values->size());
3613:       PetscCheck(Ccsr->num_entries == (PetscInt)Ccsr->values->size(), PETSC_COMM_SELF, PETSC_ERR_COR, "C nnz %" PetscInt_FMT " != %" PetscInt_FMT, Ccsr->num_entries, (PetscInt)Ccsr->values->size());
3614:       PetscCheck(Ccsr->num_entries == Acsr->num_entries + Bcsr->num_entries, PETSC_COMM_SELF, PETSC_ERR_COR, "C nnz %" PetscInt_FMT " != %" PetscInt_FMT " + %" PetscInt_FMT, Ccsr->num_entries, Acsr->num_entries, Bcsr->num_entries);
3615:       PetscCheck(Ccusp->coords->size() == Ccsr->values->size(), PETSC_COMM_SELF, PETSC_ERR_COR, "permSize %" PetscInt_FMT " != %" PetscInt_FMT, (PetscInt)Ccusp->coords->size(), (PetscInt)Ccsr->values->size());
3616:       auto pmid = Ccusp->coords->begin();
3617:       thrust::advance(pmid, Acsr->num_entries);
3618:       PetscCall(PetscLogGpuTimeBegin());
3619:       auto zibait = thrust::make_zip_iterator(thrust::make_tuple(Acsr->values->begin(), thrust::make_permutation_iterator(Ccsr->values->begin(), Ccusp->coords->begin())));
3620:       auto zieait = thrust::make_zip_iterator(thrust::make_tuple(Acsr->values->end(), thrust::make_permutation_iterator(Ccsr->values->begin(), pmid)));
3621:       PetscCallThrust(thrust::for_each(thrust::device.on(stream), zibait, zieait, VecHIPEquals()));
3622:       auto zibbit = thrust::make_zip_iterator(thrust::make_tuple(Bcsr->values->begin(), thrust::make_permutation_iterator(Ccsr->values->begin(), pmid)));
3623:       auto ziebit = thrust::make_zip_iterator(thrust::make_tuple(Bcsr->values->end(), thrust::make_permutation_iterator(Ccsr->values->begin(), Ccusp->coords->end())));
3624:       PetscCallThrust(thrust::for_each(thrust::device.on(stream), zibbit, ziebit, VecHIPEquals()));
3625:       PetscCall(MatSeqAIJHIPSPARSEInvalidateTranspose(*C, PETSC_FALSE));
3626:       if (A->form_explicit_transpose && B->form_explicit_transpose && (*C)->form_explicit_transpose) {
3627:         PetscCheck(Ccusp->matTranspose, PETSC_COMM_SELF, PETSC_ERR_COR, "Missing transpose Mat_SeqAIJHIPSPARSEMultStruct");
3628:         PetscBool  AT = Acusp->matTranspose ? PETSC_TRUE : PETSC_FALSE, BT = Bcusp->matTranspose ? PETSC_TRUE : PETSC_FALSE;
3629:         CsrMatrix *AcsrT = AT ? (CsrMatrix *)Acusp->matTranspose->mat : NULL;
3630:         CsrMatrix *BcsrT = BT ? (CsrMatrix *)Bcusp->matTranspose->mat : NULL;
3631:         CsrMatrix *CcsrT = (CsrMatrix *)Ccusp->matTranspose->mat;
3632:         auto       vT    = CcsrT->values->begin();
3633:         if (AT) PetscCallThrust(vT = thrust::copy(thrust::device.on(stream), AcsrT->values->begin(), AcsrT->values->end(), vT));
3634:         if (BT) PetscCallThrust(thrust::copy(thrust::device.on(stream), BcsrT->values->begin(), BcsrT->values->end(), vT));
3635:         (*C)->transupdated = PETSC_TRUE;
3636:       }
3637:       PetscCall(PetscLogGpuTimeEnd());
3638:     }
3639:     PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
3640:   }
3641:   PetscCall(PetscObjectStateIncrease((PetscObject)*C));
3642:   (*C)->assembled     = PETSC_TRUE;
3643:   (*C)->was_assembled = PETSC_FALSE;
3644:   (*C)->offloadmask   = PETSC_OFFLOAD_GPU;
3645:   PetscFunctionReturn(PETSC_SUCCESS);
3646: }

3648: static PetscErrorCode MatSeqAIJCopySubArray_SeqAIJHIPSPARSE(Mat A, PetscInt n, const PetscInt idx[], PetscScalar v[])
3649: {
3650:   PetscFunctionBegin;
3651:   PetscCall(MatSeqAIJHIPSPARSE_CUPM_t::CopySubArray(A, n, idx, v));
3652:   PetscFunctionReturn(PETSC_SUCCESS);
3653: }