Actual source code: aijcupm.hpp

  1: #pragma once

  3: /* Shared CUPM (CUDA/HIP) implementations for SeqAIJCUSPARSE and SeqAIJHIPSPARSE
  4:    that do not depend on the cuSPARSE/hipSPARSE library proper.

  6:    Include ordering requirement: the vendor-specific impl header
  7:    (cusparsematimpl.h or hipsparsematimpl.h) must be included before this
  8:    header so that CsrMatrix, THRUSTINTARRAY*, THRUSTARRAY and all device-specific
  9:    struct types are visible when this header is processed.

 11:    Instantiated by:
 12:      aijcusparse.cu      (DeviceType::CUDA, using MatSeqAIJCUSPARSE_Policy)
 13:      aijhipsparse.hip.cxx (DeviceType::HIP,  using MatSeqAIJHIPSPARSE_Policy) */

 15: #include <petsc/private/cupmobject.hpp>
 16: #include <petsc/private/cupmblasinterface.hpp>
 17: #include <petsc/private/matimpl.h>
 18: #include <../src/sys/objects/device/impls/cupm/cupmthrustutility.hpp>
 19: #include <../src/mat/impls/aij/seq/aij.h>

 21: #include <thrust/device_ptr.h>
 22: #include <thrust/iterator/counting_iterator.h>
 23: #include <thrust/iterator/permutation_iterator.h>
 24: #include <thrust/functional.h>
 25: #include <thrust/fill.h>
 26: #include <thrust/tuple.h>
 27: #include <thrust/transform.h>
 28: #include <thrust/for_each.h>
 29: #include <thrust/equal.h>

 31: /* Forward declaration of SeqAIJ fallback function used inside template */
 32: PETSC_INTERN PetscErrorCode MatGetDiagonal_SeqAIJ(Mat, Vec);

 34: namespace Petsc
 35: {

 37: namespace mat
 38: {

 40: namespace aij
 41: {

 43: namespace cupm
 44: {

 46: namespace impl
 47: {

 49: // expand row_offsets to uncompressed row indices coo_i[]
 50: struct Csr2coo {
 51:   const PetscInt *row_offsets;
 52:   PetscInt       *coo_i;

 54:   Csr2coo(const PetscInt *roff, PetscInt *cooi) : row_offsets(roff), coo_i(cooi) { }

 56:   PETSC_HOSTDEVICE_INLINE_DECL void operator()(PetscInt i) const
 57:   {
 58:     for (PetscInt j = row_offsets[i]; j < row_offsets[i + 1]; ++j) coo_i[j] = i;
 59:   }
 60: };

 62: struct PetscIntToCInt {
 63:   // Caller should check overflow
 64:   PETSC_HOSTDEVICE_INLINE_DECL int operator()(PetscInt i) const { return static_cast<int>(i); }
 65: };

 67: /* --------------------------------------------------------------------------
 68:    Shared device functor: left-scale CSR rows.
 69:    cprow[i] gives the logical row index for compressed row i; NULL = identity.
 70:    -------------------------------------------------------------------------- */
 71: struct DiagonalScaleLeft_CSR_Functor {
 72:   const PetscInt    *row_ptr;
 73:   PetscScalar       *val_ptr;
 74:   const PetscScalar *lv_ptr;
 75:   const PetscInt    *cprow;

 77:   PETSC_HOSTDEVICE_INLINE_DECL void operator()(PetscInt i) const
 78:   {
 79:     const PetscInt    row = cprow ? cprow[i] : i;
 80:     const PetscScalar s   = lv_ptr[row];
 81:     for (PetscInt j = row_ptr[i]; j < row_ptr[i + 1]; j++) val_ptr[j] *= s;
 82:   }
 83: };

 85: /* --------------------------------------------------------------------------
 86:    Shared device functor: get<1>(t) = get<0>(t).
 87:    Replaces the identical VecCUDAEquals / VecHIPEquals structs.
 88:    -------------------------------------------------------------------------- */
 89: struct VecCUPMEquals {
 90:   template <typename Tuple>
 91:   PETSC_HOSTDEVICE_INLINE_DECL void operator()(Tuple t) const
 92:   {
 93:     thrust::get<1>(t) = thrust::get<0>(t);
 94:   }
 95: };

 97: /* --------------------------------------------------------------------------
 98:    Shared __global__ kernel: accumulate COO values into a CSR array.
 99:    __global__ is valid for both nvcc and hipcc; the body is identical.
100:    -------------------------------------------------------------------------- */
101: __global__ static void MatAddCOOValues(const PetscScalar kv[], PetscCount nnz, const PetscCount jmap[], const PetscCount perm[], InsertMode imode, PetscScalar a[])
102: {
103:   PetscCount       i         = blockIdx.x * blockDim.x + threadIdx.x;
104:   const PetscCount grid_size = gridDim.x * blockDim.x;
105:   for (; i < nnz; i += grid_size) {
106:     PetscScalar sum = 0.0;
107:     for (PetscCount k = jmap[i]; k < jmap[i + 1]; k++) sum += kv[perm[k]];
108:     a[i] = (imode == INSERT_VALUES ? (PetscScalar)0.0 : a[i]) + sum;
109:   }
110: }

112: /* --------------------------------------------------------------------------
113:    Shared __global__ kernel: extract the CSR diagonal.
114:    -------------------------------------------------------------------------- */
115: __global__ void GetDiagonal_CSR(const PetscInt *row, const PetscInt *col, const PetscScalar *val, const PetscInt len, PetscScalar *diag)
116: {
117:   const size_t x = blockIdx.x * blockDim.x + threadIdx.x;

119:   if (x < (size_t)len) {
120:     const PetscInt rowx = row[x], num_non0_row = row[x + 1] - rowx;
121:     PetscScalar    d = 0.0;

123:     for (PetscInt i = 0; i < num_non0_row; i++) {
124:       if (col[i + rowx] == (PetscInt)x) {
125:         d = val[i + rowx];
126:         break;
127:       }
128:     }
129:     diag[x] = d;
130:   }
131: }

133: /* --------------------------------------------------------------------------
134:    Shared __global__ kernel: sum the absolute values of each CSR row.
135:    With compressed rows, cprow maps CSR row i to its row in the matrix.
136:    -------------------------------------------------------------------------- */
137: __global__ void GetRowSumAbs_CSR(const PetscInt *rowptr, const PetscScalar *val, const PetscInt *cprow, const PetscInt m, PetscScalar *sum)
138: {
139:   const size_t i = blockIdx.x * blockDim.x + threadIdx.x;

141:   if (i < (size_t)m) {
142:     PetscReal s = 0.0;

144:     for (PetscInt k = rowptr[i]; k < rowptr[i + 1]; k++) s += PetscAbsScalar(val[k]);
145:     sum[cprow ? cprow[i] : (PetscInt)i] = s;
146:   }
147: }

149: /* ==========================================================================
150:    MatSeqAIJCUSPARSE_CUPM<T, Policy>

152:    Policy (C++11 traits class) requirements - all static methods:

154:      // Device struct types
155:      typedef ... mat_struct_type;       // Mat_SeqAIJCUSPARSE / Mat_SeqAIJHIPSPARSE
156:      typedef ... mult_struct_type;      // ...MultStruct equivalent

158:      // Storage-format constants (value of each format enumerator)
159:      static int storage_format_csr();
160:      static int storage_format_ell();
161:      static int storage_format_hyb();

163:      // Bookkeeping helpers (device-type specific)
164:      static PetscErrorCode CopyToGPU(Mat);
165:      static PetscErrorCode CopyFromGPU(Mat);
166:      static PetscErrorCode InvalidateTranspose(Mat, PetscBool);
167:      static PetscErrorCode ConvertFromSeqAIJ(Mat, MatType, MatReuse, Mat *);
168:      static const char    *mat_type_name;   // "seqaijcusparse" / "seqaijhipsparse"

170:      // Destruction helpers (device-type specific)
171:      static PetscErrorCode Destroy(Mat);
172:      static PetscErrorCode TriFactorsDestroy(void **);

174:      // Compose-function keys that differ between CUDA and HIP
175:      static const char *set_format_c;          // "MatCUSPARSESetFormat_C"        / "MatHIPSPARSESetFormat_C"
176:      static const char *set_use_cpu_solve_c;   // "MatCUSPARSESetUseCPUSolve_C"   / "MatHIPSPARSESetUseCPUSolve_C"
177:      static const char *product_seqdense_device_c; // "...seqdensecuda_C"          / "...seqdensehip_C"
178:      static const char *product_seqdense_c;    // "...seqdense_C"
179:      static const char *product_self_c;        // "...seqaijcusparse_C"           / "...seqaijhipsparse_C"
180:      static const char *seq_convert_hypre_c;   // "MatConvert_seqaijcusparse_hypre_C" / "_seqaijhipsparse_hypre_C"

182:      // Vec device-array access (device-type specific)
183:      static PetscErrorCode VecGetArrayRead  (Vec, const PetscScalar **);
184:      static PetscErrorCode VecRestoreArrayRead(Vec, const PetscScalar **);
185:      static PetscErrorCode VecGetArrayWrite (Vec, PetscScalar **);
186:      static PetscErrorCode VecRestoreArrayWrite(Vec, PetscScalar **);
187:    ========================================================================== */

189: template <device::cupm::DeviceType T, typename Policy>
190: struct MatSeqAIJCUSPARSE_CUPM : device::cupm::impl::CUPMObject<T> {
191:   PETSC_CUPMOBJECT_HEADER(T);

193:   typedef typename Policy::mat_struct_type  MatStructType;
194:   typedef typename Policy::mult_struct_type MultStructType;

196:   /* -------------------------------------------------------------------
197:      Tier 1 - Trivial
198:      ------------------------------------------------------------------- */

200:   /* MatAssemblyEnd: delegation to SeqAIJ */
201:   static PetscErrorCode AssemblyEnd(Mat A, MatAssemblyType mode) noexcept
202:   {
203:     PetscFunctionBegin;
204:     PetscCall(MatAssemblyEnd_SeqAIJ(A, mode));
205:     PetscFunctionReturn(PETSC_SUCCESS);
206:   }

208:   /* MatDuplicate */
209:   static PetscErrorCode Duplicate(Mat A, MatDuplicateOption cpvalues, Mat *B) noexcept
210:   {
211:     PetscFunctionBegin;
212:     PetscCall(MatDuplicate_SeqAIJ(A, cpvalues, B));
213:     PetscCall(Policy::ConvertFromSeqAIJ(*B, Policy::mat_type_name, MAT_INPLACE_MATRIX, B));
214:     PetscFunctionReturn(PETSC_SUCCESS);
215:   }

217:   /* MatGetCurrentMemType */
218:   static PetscErrorCode GetCurrentMemType(PETSC_UNUSED Mat A, PetscMemType *m) noexcept
219:   {
220:     PetscFunctionBegin;
221:     *m = PETSC_MEMTYPE_CUPM();
222:     PetscFunctionReturn(PETSC_SUCCESS);
223:   }

225:   /* MatCOOStructDestroy: free device jmap and perm fields */
226:   static PetscErrorCode COOStructDestroy(PetscCtxRt ctx) noexcept
227:   {
228:     MatCOOStruct_SeqAIJ *coo = *(MatCOOStruct_SeqAIJ **)ctx;

230:     PetscFunctionBegin;
231:     PetscCallCUPM(cupmFree(coo->perm));
232:     PetscCallCUPM(cupmFree(coo->jmap));
233:     PetscCall(PetscFree(coo));
234:     PetscFunctionReturn(PETSC_SUCCESS);
235:   }

237:   /* -------------------------------------------------------------------
238:      Tier 2 - Straightforward
239:      ------------------------------------------------------------------- */

241:   /* MatZeroEntries: fill device CSR values with zero */
242:   static PetscErrorCode ZeroEntries(Mat A) noexcept
243:   {
244:     PetscBool          gpu = PETSC_FALSE;
245:     Mat_SeqAIJ        *a   = (Mat_SeqAIJ *)A->data;
246:     MatStructType     *spptr;
247:     cupmStream_t       stream;
248:     PetscDeviceContext dctx;

250:     PetscFunctionBegin;
251:     PetscCall(GetHandles_(&dctx, &stream));
252:     if (A->factortype == MAT_FACTOR_NONE) {
253:       spptr = (MatStructType *)A->spptr;
254:       if (spptr->mat) {
255:         CsrMatrix *matrix = (CsrMatrix *)spptr->mat->mat;
256:         if (matrix->values) {
257:           gpu = PETSC_TRUE;
258:           PetscCallThrust(THRUST_CALL(thrust::fill, stream, matrix->values->begin(), matrix->values->end(), (PetscScalar)0.));
259:         }
260:       }
261:       if (spptr->matTranspose) {
262:         CsrMatrix *matrix = (CsrMatrix *)spptr->matTranspose->mat;
263:         if (matrix->values) PetscCallThrust(THRUST_CALL(thrust::fill, stream, matrix->values->begin(), matrix->values->end(), (PetscScalar)0.));
264:       }
265:     }
266:     if (gpu) A->offloadmask = PETSC_OFFLOAD_GPU;
267:     else {
268:       PetscCall(PetscArrayzero(a->a, a->i[A->rmap->n]));
269:       A->offloadmask = PETSC_OFFLOAD_CPU;
270:     }
271:     PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
272:     PetscFunctionReturn(PETSC_SUCCESS);
273:   }

275:   /* MatScale: cupmBlasXscal on the device CSR values */
276:   static PetscErrorCode Scale(Mat Y, PetscScalar a) noexcept
277:   {
278:     Mat_SeqAIJ        *y  = (Mat_SeqAIJ *)Y->data;
279:     PetscScalar       *ay = nullptr;
280:     cupmBlasHandle_t   blashandle;
281:     PetscBLASInt       one = 1, bnz = 1;
282:     PetscDeviceContext dctx;

284:     PetscFunctionBegin;
285:     PetscCall(GetArray(Y, &ay));
286:     PetscCall(GetHandles_(&dctx, &blashandle));
287:     PetscCall(PetscBLASIntCast(y->nz, &bnz));
288:     PetscCall(PetscLogGpuTimeBegin());
289:     PetscCallCUPMBLAS(cupmBlasXscal(blashandle, bnz, cupmScalarPtrCast(&a), cupmScalarPtrCast(ay), one));
290:     PetscCall(PetscLogGpuFlops(bnz));
291:     PetscCall(PetscLogGpuTimeEnd());
292:     PetscCall(RestoreArray(Y, &ay));
293:     PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
294:     PetscFunctionReturn(PETSC_SUCCESS);
295:   }

297:   /* MatDiagonalScale: Thrust-based left and right scaling of CSR values */
298:   static PetscErrorCode DiagonalScale(Mat A, Vec ll, Vec rr) noexcept
299:   {
300:     Mat_SeqAIJ        *aij = (Mat_SeqAIJ *)A->data;
301:     MatStructType     *devstruct;
302:     CsrMatrix         *csr;
303:     PetscScalar       *av = nullptr;
304:     PetscInt           m, n, nz = aij->nz;
305:     cupmStream_t       stream;
306:     PetscDeviceContext dctx;

308:     PetscFunctionBegin;
309:     PetscCall(GetHandles_(&dctx, &stream));
310:     PetscCall(PetscLogGpuTimeBegin());
311:     PetscCall(GetArray(A, &av));
312:     devstruct = (MatStructType *)A->spptr;
313:     csr       = (CsrMatrix *)devstruct->mat->mat;
314:     if (ll) {
315:       const PetscScalar *lv;
316:       PetscCall(VecGetLocalSize(ll, &m));
317:       PetscCheck(m == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Left scaling vector wrong length");
318:       PetscCall(Policy::VecGetArrayRead(ll, &lv));
319:       {
320:         const PetscInt               *cprow   = devstruct->mat->cprowIndices ? devstruct->mat->cprowIndices->data().get() : NULL;
321:         DiagonalScaleLeft_CSR_Functor functor = {csr->row_offsets->data().get(), av, lv, cprow};
322:         PetscCallThrust(THRUST_CALL(thrust::for_each, stream, thrust::counting_iterator<PetscInt>(0), thrust::counting_iterator<PetscInt>(csr->num_rows), functor));
323:       }
324:       PetscCall(Policy::VecRestoreArrayRead(ll, &lv));
325:       PetscCall(PetscLogGpuFlops(nz));
326:     }
327:     if (rr) {
328:       const PetscScalar *rv;
329:       PetscCall(VecGetLocalSize(rr, &n));
330:       PetscCheck(n == A->cmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Right scaling vector wrong length");
331:       PetscCall(Policy::VecGetArrayRead(rr, &rv));
332: #if PetscDefined(USING_NVCC) && CCCL_VERSION >= 3001000
333:       PetscCallThrust(THRUST_CALL(thrust::transform, stream, csr->values->begin(), csr->values->end(), thrust::make_permutation_iterator(thrust::device_pointer_cast(rv), csr->column_indices->begin()), csr->values->begin(), cuda::std::multiplies<PetscScalar>()));
334: #else
335:       PetscCallThrust(THRUST_CALL(thrust::transform, stream, csr->values->begin(), csr->values->end(), thrust::make_permutation_iterator(thrust::device_pointer_cast(rv), csr->column_indices->begin()), csr->values->begin(), thrust::multiplies<PetscScalar>()));
336: #endif
337:       PetscCall(Policy::VecRestoreArrayRead(rr, &rv));
338:       PetscCall(PetscLogGpuFlops(nz));
339:     }
340:     PetscCall(RestoreArray(A, &av));
341:     PetscCall(PetscLogGpuTimeEnd());
342:     PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
343:     PetscFunctionReturn(PETSC_SUCCESS);
344:   }

346:   /* MatSeqAIJGetIJ: return device CSR row-pointer and column-index arrays */
347:   static PetscErrorCode GetIJ(Mat A, PetscBool compressed, const PetscInt **i, const PetscInt **j) noexcept
348:   {
349:     MatStructType     *cusp = (MatStructType *)A->spptr;
350:     Mat_SeqAIJ        *a    = (Mat_SeqAIJ *)A->data;
351:     CsrMatrix         *csr;
352:     cupmStream_t       stream;
353:     PetscDeviceContext dctx;

355:     PetscFunctionBegin;
356:     PetscCall(GetHandles_(&dctx, &stream));
358:     if (!i || !j) PetscFunctionReturn(PETSC_SUCCESS);
359:     PetscCheckTypeName(A, Policy::mat_type_name);
360:     PetscCheck(cusp->format != (decltype(cusp->format))Policy::storage_format_ell() && cusp->format != (decltype(cusp->format))Policy::storage_format_hyb(), PETSC_COMM_SELF, PETSC_ERR_SUP, "Not implemented");
361:     PetscCall(Policy::CopyToGPU(A));
362:     PetscCheck(cusp->mat, PETSC_COMM_SELF, PETSC_ERR_COR, "Missing MultStruct");
363:     csr = (CsrMatrix *)cusp->mat->mat;
364:     if (i) {
365:       if (!compressed && a->compressedrow.use) { /* need full row offset */
366:         if (!cusp->rowoffsets_gpu) {
367:           cusp->rowoffsets_gpu = new THRUSTINTARRAY(A->rmap->n + 1);
368:           PetscCallCUPM(cupmMemcpyAsync(cusp->rowoffsets_gpu->data().get(), a->i, (A->rmap->n + 1) * sizeof(*a->i), cupmMemcpyHostToDevice, stream));
369:           PetscCall(PetscDeviceContextSynchronize(dctx));
370:           PetscCall(PetscLogCpuToGpu((A->rmap->n + 1) * sizeof(PetscInt)));
371:         }
372:         *i = cusp->rowoffsets_gpu->data().get();
373:       } else *i = csr->row_offsets->data().get();
374:     }
375:     if (j) *j = csr->column_indices->data().get();
376:     PetscFunctionReturn(PETSC_SUCCESS);
377:   }

379:   /* MatSeqAIJRestoreIJ: nullify the pointers previously obtained with GetIJ */
380:   static PetscErrorCode RestoreIJ(Mat A, PetscBool compressed, const PetscInt **i, const PetscInt **j) noexcept
381:   {
382:     PetscFunctionBegin;
384:     PetscCheckTypeName(A, Policy::mat_type_name);
385:     if (i) *i = NULL;
386:     if (j) *j = NULL;
387:     (void)compressed;
388:     PetscFunctionReturn(PETSC_SUCCESS);
389:   }

391:   /* MatSetPreallocationCOO: copy COO bookkeeping struct to device */
392:   static PetscErrorCode SetPreallocationCOO(Mat mat, PetscCount coo_n, PetscInt coo_i[], PetscInt coo_j[]) noexcept
393:   {
394:     PetscBool            dev_ij = PETSC_FALSE;
395:     PetscMemType         mtype  = PETSC_MEMTYPE_HOST;
396:     PetscInt            *i, *j;
397:     PetscContainer       container_h;
398:     MatCOOStruct_SeqAIJ *coo_h, *coo_d;
399:     cupmStream_t         stream;
400:     PetscDeviceContext   dctx;

402:     PetscFunctionBegin;
403:     PetscCall(GetHandles_(&dctx, &stream));
404:     PetscCall(PetscGetMemType(coo_i, &mtype));
405:     if (PetscMemTypeDevice(mtype)) {
406:       dev_ij = PETSC_TRUE;
407:       PetscCall(PetscMalloc2(coo_n, &i, coo_n, &j));
408:       PetscCallCUPM(cupmMemcpyAsync(i, coo_i, coo_n * sizeof(PetscInt), cupmMemcpyDeviceToHost, stream));
409:       PetscCallCUPM(cupmMemcpyAsync(j, coo_j, coo_n * sizeof(PetscInt), cupmMemcpyDeviceToHost, stream));
410:       PetscCall(PetscDeviceContextSynchronize(dctx));
411:     } else {
412:       i = coo_i;
413:       j = coo_j;
414:     }
415:     PetscCall(MatSetPreallocationCOO_SeqAIJ(mat, coo_n, i, j));
416:     if (dev_ij) PetscCall(PetscFree2(i, j));
417:     mat->offloadmask = PETSC_OFFLOAD_CPU;
418:     /* Create the GPU memory */
419:     PetscCall(Policy::CopyToGPU(mat));

421:     /* Copy the COO struct to device */
422:     PetscCall(PetscObjectQuery((PetscObject)mat, "__PETSc_MatCOOStruct_Host", (PetscObject *)&container_h));
423:     PetscCall(PetscContainerGetPointer(container_h, (void **)&coo_h));
424:     PetscCall(PetscMalloc1(1, &coo_d));
425:     *coo_d = *coo_h; /* shallow copy; device fields amended below */
426:     PetscCallCUPM(cupmMalloc((void **)&coo_d->jmap, (coo_h->nz + 1) * sizeof(PetscCount)));
427:     PetscCallCUPM(cupmMemcpyAsync(coo_d->jmap, coo_h->jmap, (coo_h->nz + 1) * sizeof(PetscCount), cupmMemcpyHostToDevice, stream));
428:     PetscCallCUPM(cupmMalloc((void **)&coo_d->perm, coo_h->Atot * sizeof(PetscCount)));
429:     PetscCallCUPM(cupmMemcpyAsync(coo_d->perm, coo_h->perm, coo_h->Atot * sizeof(PetscCount), cupmMemcpyHostToDevice, stream));
430:     PetscCall(PetscDeviceContextSynchronize(dctx));

432:     PetscCall(PetscObjectContainerCompose((PetscObject)mat, "__PETSc_MatCOOStruct_Device", coo_d, MatSeqAIJCUSPARSE_CUPM::COOStructDestroy));
433:     PetscFunctionReturn(PETSC_SUCCESS);
434:   }

436:   /* MatSetValuesCOO: launch MatAddCOOValues kernel */
437:   static PetscErrorCode SetValuesCOO(Mat A, const PetscScalar v[], InsertMode imode) noexcept
438:   {
439:     Mat_SeqAIJ          *seq  = (Mat_SeqAIJ *)A->data;
440:     MatStructType       *dev  = (MatStructType *)A->spptr;
441:     PetscCount           Annz = seq->nz;
442:     PetscMemType         memtype;
443:     const PetscScalar   *v1 = v;
444:     PetscScalar         *Aa = nullptr;
445:     PetscContainer       container;
446:     MatCOOStruct_SeqAIJ *coo;
447:     cupmStream_t         stream;
448:     PetscDeviceContext   dctx;

450:     PetscFunctionBegin;
451:     PetscCall(MatSeqAIJCheckCOONonzeroState(A));
452:     PetscCall(GetHandles_(&dctx, &stream));
453:     if (!dev->mat) PetscCall(Policy::CopyToGPU(A));

455:     PetscCall(PetscObjectQuery((PetscObject)A, "__PETSc_MatCOOStruct_Device", (PetscObject *)&container));
456:     PetscCall(PetscContainerGetPointer(container, (void **)&coo));

458:     PetscCall(PetscGetMemType(v, &memtype));
459:     if (PetscMemTypeHost(memtype)) { /* copy host values to device */
460:       PetscCallCUPM(cupmMalloc((void **)&v1, coo->n * sizeof(PetscScalar)));
461:       PetscCallCUPM(cupmMemcpyAsync((void *)v1, v, coo->n * sizeof(PetscScalar), cupmMemcpyHostToDevice, stream));
462:       // The caller may reuse the host values after this call returns.
463:       PetscCall(PetscDeviceContextSynchronize(dctx));
464:       PetscCall(PetscLogCpuToGpu(coo->n * sizeof(PetscScalar)));
465:     }

467:     if (imode == INSERT_VALUES) PetscCall(GetArrayWrite(A, &Aa));
468:     else PetscCall(GetArray(A, &Aa));

470:     PetscCall(PetscLogGpuTimeBegin());
471:     if (Annz) {
472:       PetscCallCUPM(cupmLaunchKernel(MatAddCOOValues, (unsigned int)((Annz + 255) / 256), 256u, (size_t)0, stream, v1, Annz, coo->jmap, coo->perm, imode, Aa));
473:       PetscCallCUPM(cupmGetLastError());
474:     }
475:     PetscCall(PetscLogGpuTimeEnd());

477:     if (imode == INSERT_VALUES) PetscCall(RestoreArrayWrite(A, &Aa));
478:     else PetscCall(RestoreArray(A, &Aa));

480:     if (PetscMemTypeHost(memtype)) {
481:       void *v1_device = (void *)v1;

483:       PetscCallCUPM(cupmFreeAsync(v1_device, stream));
484:     }
485:     PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
486:     PetscFunctionReturn(PETSC_SUCCESS);
487:   }

489:   /* MatSeqAIJCopySubArray: scatter-gather a sub-array of CSR values */
490:   static PetscErrorCode CopySubArray(Mat A, PetscInt n, const PetscInt idx[], PetscScalar v[]) noexcept
491:   {
492:     const PetscScalar *av = nullptr;
493:     PetscMemType       mtype;
494:     PetscBool          dmem;
495:     cupmStream_t       stream;
496:     PetscDeviceContext dctx;

498:     PetscFunctionBegin;
499:     PetscCall(GetHandles_(&dctx, &stream));
500:     PetscCall(PetscCUPMGetMemType(v, &mtype));
501:     dmem = PetscMemTypeDevice(mtype);
502:     PetscCall(GetArrayRead(A, &av));
503:     if (n && idx) {
504:       THRUSTINTARRAY widx(n);
505:       PetscCallCUPM(cupmMemcpyAsync(widx.data().get(), idx, n * sizeof(*idx), cupmMemcpyHostToDevice, stream));
506:       PetscCall(PetscLogCpuToGpu(n * sizeof(PetscInt)));

508:       THRUSTARRAY                    *w = NULL;
509:       thrust::device_ptr<PetscScalar> dv;
510:       if (dmem) {
511:         dv = thrust::device_pointer_cast(v);
512:       } else {
513:         w  = new THRUSTARRAY(n);
514:         dv = w->data();
515:       }
516:       {
517:         thrust::device_ptr<const PetscScalar> dav   = thrust::device_pointer_cast(av);
518:         auto                                  zibit = thrust::make_zip_iterator(thrust::make_tuple(thrust::make_permutation_iterator(dav, widx.begin()), dv));
519:         auto                                  zieit = thrust::make_zip_iterator(thrust::make_tuple(thrust::make_permutation_iterator(dav, widx.end()), dv + n));
520:         PetscCallThrust(THRUST_CALL(thrust::for_each, stream, zibit, zieit, VecCUPMEquals{}));
521:       }
522:       if (w) PetscCallCUPM(cupmMemcpyAsync(v, w->data().get(), n * sizeof(PetscScalar), cupmMemcpyDeviceToHost, stream));
523:       // Complete the gather before its temporary device indices are destroyed.
524:       PetscCall(PetscDeviceContextSynchronize(dctx));
525:       delete w;
526:     } else {
527:       PetscCallCUPM(cupmMemcpyAsync(v, av, n * sizeof(PetscScalar), dmem ? cupmMemcpyDeviceToDevice : cupmMemcpyDeviceToHost, stream));
528:       if (dmem) PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
529:       else PetscCall(PetscDeviceContextSynchronize(dctx));
530:     }
531:     if (!dmem) PetscCall(PetscLogCpuToGpu(n * sizeof(PetscScalar)));
532:     PetscCall(RestoreArrayRead(A, &av));
533:     PetscFunctionReturn(PETSC_SUCCESS);
534:   }

536:   /* -------------------------------------------------------------------
537:      Tier 3 - AXPY shared branches (SAME_NZ and DIFFERENT_NZ only).
538:      The SUBSET_NZ branch calls cuSPARSE/hipSPARSE and stays in the caller.
539:      ------------------------------------------------------------------- */

541:   /* AXPY SAME_NONZERO_PATTERN branch: cupmBlasXaxpy */
542:   static PetscErrorCode AXPY_SameNZ(Mat Y, PetscScalar a, Mat X) noexcept
543:   {
544:     Mat_SeqAIJ        *x  = (Mat_SeqAIJ *)X->data;
545:     const PetscScalar *ax = nullptr;
546:     PetscScalar       *ay = nullptr;
547:     cupmBlasHandle_t   blashandle;
548:     PetscBLASInt       one = 1, bnz = 1;
549:     PetscDeviceContext dctx;

551:     PetscFunctionBegin;
552:     PetscCall(GetArrayRead(X, &ax));
553:     PetscCall(GetArray(Y, &ay));
554:     PetscCall(GetHandles_(&dctx, &blashandle));
555:     PetscCall(PetscBLASIntCast(x->nz, &bnz));
556:     PetscCall(PetscLogGpuTimeBegin());
557:     PetscCallCUPMBLAS(cupmBlasXaxpy(blashandle, bnz, cupmScalarPtrCast(&a), cupmScalarPtrCast(ax), one, cupmScalarPtrCast(ay), one));
558:     PetscCall(PetscLogGpuFlops(2.0 * bnz));
559:     PetscCall(PetscLogGpuTimeEnd());
560:     PetscCall(RestoreArrayRead(X, &ax));
561:     PetscCall(RestoreArray(Y, &ay));
562:     PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
563:     PetscFunctionReturn(PETSC_SUCCESS);
564:   }

566:   /* GetDiagonal: kernel-based extraction of the CSR diagonal */
567:   static PetscErrorCode GetDiagonal(Mat A, Vec diag) noexcept
568:   {
569:     MatStructType  *devstruct = (MatStructType *)A->spptr;
570:     MultStructType *matstruct = (MultStructType *)devstruct->mat;
571:     PetscScalar    *darray;
572:     cupmStream_t    stream;

574:     PetscFunctionBegin;
575:     if (A->offloadmask == PETSC_OFFLOAD_BOTH || A->offloadmask == PETSC_OFFLOAD_GPU) {
576:       PetscInt   n   = A->rmap->n;
577:       CsrMatrix *mat = (CsrMatrix *)matstruct->mat;

579:       PetscCheck(devstruct->format == (decltype(devstruct->format))Policy::storage_format_csr(), PETSC_COMM_SELF, PETSC_ERR_SUP, "Only CSR format supported");
580:       if (n > 0) {
581:         PetscDeviceContext dctx;

583:         PetscCall(Policy::VecGetArrayWrite(diag, &darray));
584:         PetscCall(GetHandles_(&dctx, &stream));
585:         PetscCallCUPM(cupmLaunchKernel(GetDiagonal_CSR, (unsigned int)((n + 255) / 256), 256u, (size_t)0, stream, mat->row_offsets->data().get(), mat->column_indices->data().get(), mat->values->data().get(), n, darray));
586:         PetscCallCUPM(cupmGetLastError());
587:         PetscCall(Policy::VecRestoreArrayWrite(diag, &darray));
588:         PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
589:       }
590:     } else {
591:       PetscCall(MatGetDiagonal_SeqAIJ(A, diag));
592:     }
593:     PetscFunctionReturn(PETSC_SUCCESS);
594:   }

596:   /* GetRowSumAbs: kernel-based sum of the absolute values of each CSR row */
597:   static PetscErrorCode GetRowSumAbs(Mat A, Vec v) noexcept
598:   {
599:     PetscInt n;

601:     PetscFunctionBegin;
602:     PetscCheck(!A->factortype, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
603:     PetscCall(VecGetLocalSize(v, &n));
604:     PetscCheck(n == A->rmap->n, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Nonconforming matrix and vector");
605:     if (A->offloadmask == PETSC_OFFLOAD_BOTH || A->offloadmask == PETSC_OFFLOAD_GPU) {
606:       MatStructType  *devstruct = (MatStructType *)A->spptr;
607:       MultStructType *matstruct = (MultStructType *)devstruct->mat;
608:       CsrMatrix      *mat       = (CsrMatrix *)matstruct->mat;
609:       const PetscInt  m         = mat->num_rows;
610:       const PetscInt *cprow     = matstruct->cprowIndices ? matstruct->cprowIndices->data().get() : nullptr;
611:       PetscScalar    *varray;
612:       cupmStream_t    stream;

614:       PetscCheck(devstruct->format == (decltype(devstruct->format))Policy::storage_format_csr(), PETSC_COMM_SELF, PETSC_ERR_SUP, "Only CSR format supported");
615:       if (n > 0) {
616:         PetscDeviceContext dctx;

618:         PetscCall(Policy::VecGetArrayWrite(v, &varray));
619:         PetscCall(GetHandles_(&dctx, &stream));
620:         // compressed rows leave the empty rows unwritten by the kernel
621:         if (matstruct->cprowIndices) PetscCallCUPM(cupmMemsetAsync(varray, 0, n * sizeof(*varray), stream));
622:         if (m > 0) {
623:           PetscCallCUPM(cupmLaunchKernel(GetRowSumAbs_CSR, (unsigned int)((m + 255) / 256), 256u, (size_t)0, stream, mat->row_offsets->data().get(), mat->values->data().get(), cprow, m, varray));
624:           PetscCallCUPM(cupmGetLastError());
625:         }
626:         PetscCall(Policy::VecRestoreArrayWrite(v, &varray));
627:         PetscCall(PetscLogGpuFlops(mat->num_entries));
628:         PetscCall(PetscDeviceContextSynchronizeIfWithBarrier_Internal(dctx));
629:       }
630:     } else PetscCall(MatGetRowSumAbs_SeqAIJ(A, v));
631:     PetscFunctionReturn(PETSC_SUCCESS);
632:   }

634:   /* -------------------------------------------------------------------
635:      Tier 4 - Device array access (moved here from vendor files so both
636:      SeqAIJCUSPARSE and SeqAIJHIPSPARSE share one implementation).
637:      ------------------------------------------------------------------- */

639:   /* GetArrayRead: read-only access to device CSR value array */
640:   static PetscErrorCode GetArrayRead(Mat A, const PetscScalar **a) noexcept
641:   {
642:     MatStructType *cusp = (MatStructType *)A->spptr;
643:     CsrMatrix     *csr;

645:     PetscFunctionBegin;
647:     PetscAssertPointer(a, 2);
648:     PetscCheckTypeName(A, Policy::mat_type_name);
649:     PetscCheck(cusp->format != (decltype(cusp->format))Policy::storage_format_ell() && cusp->format != (decltype(cusp->format))Policy::storage_format_hyb(), PETSC_COMM_SELF, PETSC_ERR_SUP, "Not implemented");
650:     PetscCall(Policy::CopyToGPU(A));
651:     PetscCheck(cusp->mat, PETSC_COMM_SELF, PETSC_ERR_COR, "Missing MultStruct");
652:     csr = (CsrMatrix *)cusp->mat->mat;
653:     PetscCheck(csr->values, PETSC_COMM_SELF, PETSC_ERR_COR, "Missing device memory");
654:     *a = csr->values->data().get();
655:     PetscFunctionReturn(PETSC_SUCCESS);
656:   }

658:   /* RestoreArrayRead: release read-only access obtained from GetArrayRead */
659:   static PetscErrorCode RestoreArrayRead(Mat A, const PetscScalar **a) noexcept
660:   {
661:     PetscFunctionBegin;
663:     PetscAssertPointer(a, 2);
664:     PetscCheckTypeName(A, Policy::mat_type_name);
665:     *a = NULL;
666:     PetscFunctionReturn(PETSC_SUCCESS);
667:   }

669:   /* GetArray: read-write access to device CSR value array */
670:   static PetscErrorCode GetArray(Mat A, PetscScalar **a) noexcept
671:   {
672:     MatStructType *cusp = (MatStructType *)A->spptr;
673:     CsrMatrix     *csr;

675:     PetscFunctionBegin;
677:     PetscAssertPointer(a, 2);
678:     PetscCheckTypeName(A, Policy::mat_type_name);
679:     PetscCheck(cusp->format != (decltype(cusp->format))Policy::storage_format_ell() && cusp->format != (decltype(cusp->format))Policy::storage_format_hyb(), PETSC_COMM_SELF, PETSC_ERR_SUP, "Not implemented");
680:     PetscCall(Policy::CopyToGPU(A));
681:     PetscCheck(cusp->mat, PETSC_COMM_SELF, PETSC_ERR_COR, "Missing MultStruct");
682:     csr = (CsrMatrix *)cusp->mat->mat;
683:     PetscCheck(csr->values, PETSC_COMM_SELF, PETSC_ERR_COR, "Missing device memory");
684:     *a             = csr->values->data().get();
685:     A->offloadmask = PETSC_OFFLOAD_GPU;
686:     PetscCall(Policy::InvalidateTranspose(A, PETSC_FALSE));
687:     PetscFunctionReturn(PETSC_SUCCESS);
688:   }

690:   /* RestoreArray: restore read-write access obtained from GetArray */
691:   static PetscErrorCode RestoreArray(Mat A, PetscScalar **a) noexcept
692:   {
693:     PetscFunctionBegin;
695:     PetscAssertPointer(a, 2);
696:     PetscCheckTypeName(A, Policy::mat_type_name);
697:     PetscCall(PetscObjectStateIncrease((PetscObject)A));
698:     *a = NULL;
699:     PetscFunctionReturn(PETSC_SUCCESS);
700:   }

702:   /* GetArrayWrite: write-only access to device CSR value array (no host-to-device copy) */
703:   static PetscErrorCode GetArrayWrite(Mat A, PetscScalar **a) noexcept
704:   {
705:     MatStructType *cusp = (MatStructType *)A->spptr;
706:     CsrMatrix     *csr;

708:     PetscFunctionBegin;
710:     PetscAssertPointer(a, 2);
711:     PetscCheckTypeName(A, Policy::mat_type_name);
712:     PetscCheck(cusp->format != (decltype(cusp->format))Policy::storage_format_ell() && cusp->format != (decltype(cusp->format))Policy::storage_format_hyb(), PETSC_COMM_SELF, PETSC_ERR_SUP, "Not implemented");
713:     PetscCheck(cusp->mat, PETSC_COMM_SELF, PETSC_ERR_COR, "Missing MultStruct");
714:     csr = (CsrMatrix *)cusp->mat->mat;
715:     PetscCheck(csr->values, PETSC_COMM_SELF, PETSC_ERR_COR, "Missing device memory");
716:     *a             = csr->values->data().get();
717:     A->offloadmask = PETSC_OFFLOAD_GPU;
718:     PetscCall(Policy::InvalidateTranspose(A, PETSC_FALSE));
719:     PetscFunctionReturn(PETSC_SUCCESS);
720:   }

722:   /* RestoreArrayWrite: restore write-only access obtained from GetArrayWrite */
723:   static PetscErrorCode RestoreArrayWrite(Mat A, PetscScalar **a) noexcept
724:   {
725:     PetscFunctionBegin;
727:     PetscAssertPointer(a, 2);
728:     PetscCheckTypeName(A, Policy::mat_type_name);
729:     PetscCall(PetscObjectStateIncrease((PetscObject)A));
730:     *a = NULL;
731:     PetscFunctionReturn(PETSC_SUCCESS);
732:   }

734:   /* SeqAIJGetArray: copy GPU-to-CPU then return host value array (ops->getarray) */
735:   static PetscErrorCode SeqAIJGetArray(Mat A, PetscScalar *array[]) noexcept
736:   {
737:     PetscFunctionBegin;
738:     PetscCall(Policy::CopyFromGPU(A));
739:     *array = ((Mat_SeqAIJ *)A->data)->a;
740:     PetscFunctionReturn(PETSC_SUCCESS);
741:   }

743:   /* SeqAIJRestoreArray: mark matrix data CPU-valid (ops->restorearray) */
744:   static PetscErrorCode SeqAIJRestoreArray(Mat A, PetscScalar *array[]) noexcept
745:   {
746:     PetscFunctionBegin;
747:     A->offloadmask = PETSC_OFFLOAD_CPU;
748:     *array         = NULL;
749:     PetscFunctionReturn(PETSC_SUCCESS);
750:   }

752:   /* SeqAIJGetArrayRead: copy GPU-to-CPU then return host value array read-only (ops->getarrayread) */
753:   static PetscErrorCode SeqAIJGetArrayRead(Mat A, const PetscScalar *array[]) noexcept
754:   {
755:     PetscFunctionBegin;
756:     PetscCall(Policy::CopyFromGPU(A));
757:     *array = ((Mat_SeqAIJ *)A->data)->a;
758:     PetscFunctionReturn(PETSC_SUCCESS);
759:   }

761:   /* SeqAIJRestoreArrayRead: release read-only host array (ops->restorearrayread) */
762:   static PetscErrorCode SeqAIJRestoreArrayRead(Mat /*A*/, const PetscScalar *array[]) noexcept
763:   {
764:     PetscFunctionBegin;
765:     *array = NULL;
766:     PetscFunctionReturn(PETSC_SUCCESS);
767:   }

769:   /* SeqAIJGetArrayWrite: return host value array for write-only access (ops->getarraywrite) */
770:   static PetscErrorCode SeqAIJGetArrayWrite(Mat A, PetscScalar *array[]) noexcept
771:   {
772:     PetscFunctionBegin;
773:     *array = ((Mat_SeqAIJ *)A->data)->a;
774:     PetscFunctionReturn(PETSC_SUCCESS);
775:   }

777:   /* SeqAIJRestoreArrayWrite: mark matrix data CPU-valid after write (ops->restorearraywrite) */
778:   static PetscErrorCode SeqAIJRestoreArrayWrite(Mat A, PetscScalar *array[]) noexcept
779:   {
780:     PetscFunctionBegin;
781:     A->offloadmask = PETSC_OFFLOAD_CPU;
782:     *array         = NULL;
783:     PetscFunctionReturn(PETSC_SUCCESS);
784:   }

786:   /* CreateSeqAIJ: allocate and preallocate a seq sparse matrix of this type */
787:   static PetscErrorCode CreateSeqAIJ(MPI_Comm comm, PetscInt m, PetscInt n, PetscInt nz, const PetscInt nnz[], Mat *A) noexcept
788:   {
789:     PetscFunctionBegin;
790:     PetscCall(MatCreate(comm, A));
791:     PetscCall(MatSetSizes(*A, m, n, m, n));
792:     PetscCall(MatSetType(*A, Policy::mat_type_name));
793:     PetscCall(MatSeqAIJSetPreallocation_SeqAIJ(*A, nz, (PetscInt *)nnz));
794:     PetscFunctionReturn(PETSC_SUCCESS);
795:   }

797:   /* MatDestroy: free vendor-specific state, deregister composed functions */
798:   static PetscErrorCode Destroy(Mat A) noexcept
799:   {
800:     PetscFunctionBegin;
801:     if (A->factortype == MAT_FACTOR_NONE) PetscCall(Policy::Destroy(A));
802:     else PetscCall(Policy::TriFactorsDestroy(&A->spptr));
803:     PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSeqAIJCopySubArray_C", NULL));
804:     PetscCall(PetscObjectComposeFunction((PetscObject)A, Policy::set_format_c, NULL));
805:     PetscCall(PetscObjectComposeFunction((PetscObject)A, Policy::set_use_cpu_solve_c, NULL));
806:     PetscCall(PetscObjectComposeFunction((PetscObject)A, Policy::product_seqdense_device_c, NULL));
807:     PetscCall(PetscObjectComposeFunction((PetscObject)A, Policy::product_seqdense_c, NULL));
808:     PetscCall(PetscObjectComposeFunction((PetscObject)A, Policy::product_self_c, NULL));
809:     PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatFactorGetSolverType_C", NULL));
810:     PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSetPreallocationCOO_C", NULL));
811:     PetscCall(PetscObjectComposeFunction((PetscObject)A, "MatSetValuesCOO_C", NULL));
812:     PetscCall(PetscObjectComposeFunction((PetscObject)A, Policy::seq_convert_hypre_c, NULL));
813:     PetscCall(MatDestroy_SeqAIJ(A));
814:     PetscFunctionReturn(PETSC_SUCCESS);
815:   }
816: };

818: } // namespace impl

820: } // namespace cupm

822: } // namespace aij

824: } // namespace mat

826: } // namespace Petsc