Actual source code: veccupmimpl.h

  1: #pragma once

  3: #include <petsc/private/vecimpl.h>
  4: #include <../src/vec/vec/impls/dvecimpl.h>

  6: #if PetscDefined(HAVE_NVSHMEM)
  7: PETSC_INTERN PetscErrorCode PetscNvshmemInitializeCheck(void);
  8: PETSC_INTERN PetscErrorCode PetscNvshmemMalloc(size_t, void **);
  9: PETSC_INTERN PetscErrorCode PetscNvshmemCalloc(size_t, void **);
 10: PETSC_INTERN PetscErrorCode PetscNvshmemFree_Private(void *);
 11:   #define PetscNvshmemFree(ptr) ((PetscErrorCode)((ptr) && (PetscNvshmemFree_Private(ptr) || ((ptr) = PETSC_NULLPTR, PETSC_SUCCESS))))
 12: PETSC_INTERN PetscErrorCode PetscNvshmemSum(PetscInt, PetscScalar *, const PetscScalar *);
 13: PETSC_INTERN PetscErrorCode PetscNvshmemMax(PetscInt, PetscReal *, const PetscReal *);
 14: #else
 15:   #define PetscNvshmemFree(ptr) PETSC_SUCCESS
 16: #endif

 18: #if defined(__cplusplus) && PetscDefined(HAVE_DEVICE)
 19: #include <petsc/private/deviceimpl.h>
 20: #include <petsc/private/cupmobject.hpp>
 21: #include <petsc/private/cupmblasinterface.hpp>

 23: #include <petsc/private/cpp/functional.hpp>

 25:   #include <limits> // std::numeric_limits

 27: namespace Petsc
 28: {

 30: namespace vec
 31: {

 33: namespace cupm
 34: {

 36: namespace impl
 37: {

 39: namespace
 40: {

 42: struct no_op {
 43:   template <typename... T>
 44:   constexpr PetscErrorCode operator()(T &&...) const noexcept
 45:   {
 46:     return PETSC_SUCCESS;
 47:   }
 48: };

 50: template <typename T>
 51: struct CooPair {
 52:   using value_type = T;
 53:   using size_type  = PetscCount;

 55:   value_type *&device;
 56:   value_type *&host;
 57:   size_type    size;
 58: };

 60: template <typename U>
 61: static constexpr CooPair<U> make_coo_pair(U *&device, U *&host, PetscCount size) noexcept
 62: {
 63:   return {device, host, size};
 64: }

 66: } // anonymous namespace

 68: // forward declarations
 69: template <device::cupm::DeviceType>
 70: class PETSC_SINGLE_LIBRARY_VISIBILITY_INTERNAL VecSeq_CUPM;
 71: template <device::cupm::DeviceType>
 72: class PETSC_SINGLE_LIBRARY_VISIBILITY_INTERNAL VecMPI_CUPM;

 74: // ==========================================================================================
 75: // Vec_CUPMBase
 76: //
 77: // Base class for the VecSeq and VecMPI CUPM implementations. On top of the usual DeviceType
 78: // template parameter it also uses CRTP to be able to use values/calls specific to either
 79: // VecSeq or VecMPI. This is in effect "inside-out" polymorphism.
 80: // ==========================================================================================
 81: template <device::cupm::DeviceType T, typename Derived>
 82: class PETSC_SINGLE_LIBRARY_VISIBILITY_INTERNAL Vec_CUPMBase : protected device::cupm::impl::CUPMObject<T> {
 83: public:
 84:   PETSC_CUPMOBJECT_HEADER(T);

 86:   // ==========================================================================================
 87:   // Vec_CUPMBase::VectorArray
 88:   //
 89:   // RAII versions of the get/restore array routines. Determines constness of the pointer type,
 90:   // holds the pointer itself provides the implicit conversion operator
 91:   // ==========================================================================================
 92:   template <PetscMemType, PetscMemoryAccessMode>
 93:   class VectorArray;

 95: protected:
 96:   static PetscErrorCode VecView_Debug(Vec v, const char *message = "") noexcept
 97:   {
 98:     const auto   pobj  = PetscObjectCast(v);
 99:     const auto   vimpl = VecIMPLCast(v);
100:     const auto   vcu   = VecCUPMCast(v);
101:     PetscMemType mtype;
102:     MPI_Comm     comm;

104:     PetscFunctionBegin;
105:     PetscAssertPointer(vimpl, 1);
106:     PetscAssertPointer(vcu, 1);
107:     PetscCall(PetscObjectGetComm(pobj, &comm));
108:     PetscCall(PetscPrintf(comm, "---------- %s ----------\n", message));
109:     PetscCall(PetscObjectPrintClassNamePrefixType(pobj, PETSC_VIEWER_STDOUT_(comm)));
110:     PetscCall(PetscPrintf(comm, "Address:             %p\n", v));
111:     PetscCall(PetscPrintf(comm, "Size:                %" PetscInt_FMT "\n", v->map->n));
112:     PetscCall(PetscPrintf(comm, "Offload mask:        %s\n", PetscOffloadMaskToString(v->offloadmask)));
113:     PetscCall(PetscPrintf(comm, "Host ptr:            %p\n", vimpl->array));
114:     PetscCall(PetscPrintf(comm, "Device ptr:          %p\n", vcu->array_d));
115:     PetscCall(PetscPrintf(comm, "Device alloced ptr:  %p\n", vcu->array_allocated_d));
116:     PetscCall(PetscCUPMGetMemType(vcu->array_d, &mtype));
117:     PetscCall(PetscPrintf(comm, "dptr is device mem?  %s\n", PetscBools[static_cast<PetscBool>(PetscMemTypeDevice(mtype))]));
118:     PetscFunctionReturn(PETSC_SUCCESS);
119:   }

121:   // Delete the allocated device array if required and replace it with the given array
122:   static PetscErrorCode ResetAllocatedDevicePtr_(PetscDeviceContext, Vec, PetscScalar * = nullptr) noexcept;
123:   // Check either the host or device impl pointer is allocated and allocate it if
124:   // isn't. CastFunctionType casts the Vec to the required type and returns the pointer
125:   template <typename CastFunctionType>
126:   static PetscErrorCode VecAllocateCheck_(Vec, void *&, CastFunctionType &&) noexcept;
127:   // Check the CUPM part (v->spptr) is allocated, otherwise allocate it
128:   static PetscErrorCode VecCUPMAllocateCheck_(Vec) noexcept;
129:   // Check the Host part (v->data) is allocated, otherwise allocate it
130:   static PetscErrorCode VecIMPLAllocateCheck_(Vec) noexcept;
131:   // Check the Host array is allocated, otherwise allocate it
132:   static PetscErrorCode HostAllocateCheck_(PetscDeviceContext, Vec) noexcept;
133:   // Check the CUPM array is allocated, otherwise allocate it
134:   static PetscErrorCode DeviceAllocateCheck_(PetscDeviceContext, Vec) noexcept;
135:   // Copy HTOD, allocating device if necessary
136:   static PetscErrorCode CopyToDevice_(PetscDeviceContext, Vec, bool = false) noexcept;
137:   // Copy DTOH, allocating host if necessary
138:   static PetscErrorCode CopyToHost_(PetscDeviceContext, Vec, bool = false) noexcept;
139:   static PetscErrorCode DestroyDevice_(Vec) noexcept;
140:   static PetscErrorCode DestroyHost_(Vec) noexcept;

142: public:
143:   struct Vec_CUPM {
144:     PetscScalar *array_d;           // gpu data
145:     PetscScalar *array_allocated_d; // does PETSc own the array ptr?
146:     PetscBool    nvshmem;           // is array allocated in nvshmem? It is used to allocate
147:                                     // Mvctx->lvec in nvshmem

149:     // COO stuff
150:     PetscCount *jmap1_d; // [m+1]: i-th entry of the vector has jmap1[i+1]-jmap1[i] repeats
151:                          // in COO arrays
152:     PetscCount *perm1_d; // [tot1]: permutation array for local entries
153:     PetscCount *imap2_d; // [nnz2]: i-th unique entry in recvbuf is imap2[i]-th entry in
154:                          // the vector
155:     PetscCount *jmap2_d; // [nnz2+1]
156:     PetscCount *perm2_d; // [recvlen]
157:     PetscCount *Cperm_d; // [sendlen]: permutation array to fill sendbuf[]. 'C' for
158:                          // communication

160:     // Buffers for remote values in VecSetValuesCOO()
161:     PetscScalar *sendbuf_d;
162:     PetscScalar *recvbuf_d;
163:   };

165:   // Cast the Vec to its Vec_CUPM struct, i.e. return the result of (Vec_CUPM *)v->spptr
166:   PETSC_NODISCARD static Vec_CUPM *VecCUPMCast(Vec) noexcept;
167:   // Cast the Vec to its host struct, i.e. return the result of (Vec_Seq *)v->data
168:   template <typename U = Derived>
169:   PETSC_NODISCARD static constexpr auto VecIMPLCast(Vec v) noexcept -> decltype(U::VecIMPLCast_(v));
170:   // Get the PetscLogEvents for HTOD and DTOH
171:   PETSC_NODISCARD static constexpr PetscLogEvent VEC_CUPMCopyToGPU() noexcept;
172:   PETSC_NODISCARD static constexpr PetscLogEvent VEC_CUPMCopyFromGPU() noexcept;
173:   // Get the VecTypes
174:   PETSC_NODISCARD static constexpr VecType VECSEQCUPM() noexcept;
175:   PETSC_NODISCARD static constexpr VecType VECMPICUPM() noexcept;
176:   PETSC_NODISCARD static constexpr VecType VECCUPM() noexcept;

178:   // Get the device VecType of the calling vector
179:   template <typename U = Derived>
180:   PETSC_NODISCARD static constexpr VecType VECIMPLCUPM() noexcept;
181:   // Get the host VecType of the calling vector
182:   template <typename U = Derived>
183:   PETSC_NODISCARD static constexpr VecType VECIMPL() noexcept;

185:   // Call the host destroy function, i.e. VecDestroy_Seq()
186:   static PetscErrorCode VecDestroy_IMPL(Vec) noexcept;
187:   // Call the host reset function, i.e. VecResetArray_Seq()
188:   static PetscErrorCode VecResetArray_IMPL(Vec) noexcept;
189:   // ... you get the idea
190:   static PetscErrorCode VecPlaceArray_IMPL(Vec, const PetscScalar *) noexcept;
191:   // Call the host creation function, i.e. VecCreate_Seq(), and also initialize the CUPM part
192:   // along with it if needed
193:   static PetscErrorCode VecCreate_IMPL_Private(Vec, PetscBool *, PetscInt = 0, PetscScalar * = nullptr) noexcept;

195:   // Shorthand for creating VectorArray's. Need functions to create them, otherwise using them
196:   // as an unnamed temporary leads to most vexing parse
197:   PETSC_NODISCARD static auto DeviceArrayRead(PetscDeviceContext dctx, Vec v) noexcept PETSC_DECLTYPE_AUTO_RETURNS(VectorArray<PETSC_MEMTYPE_DEVICE, PETSC_MEMORY_ACCESS_READ>{dctx, v});
198:   PETSC_NODISCARD static auto DeviceArrayWrite(PetscDeviceContext dctx, Vec v) noexcept PETSC_DECLTYPE_AUTO_RETURNS(VectorArray<PETSC_MEMTYPE_DEVICE, PETSC_MEMORY_ACCESS_WRITE>{dctx, v});
199:   PETSC_NODISCARD static auto DeviceArrayReadWrite(PetscDeviceContext dctx, Vec v) noexcept PETSC_DECLTYPE_AUTO_RETURNS(VectorArray<PETSC_MEMTYPE_DEVICE, PETSC_MEMORY_ACCESS_READ_WRITE>{dctx, v});
200:   PETSC_NODISCARD static auto HostArrayRead(PetscDeviceContext dctx, Vec v) noexcept PETSC_DECLTYPE_AUTO_RETURNS(VectorArray<PETSC_MEMTYPE_HOST, PETSC_MEMORY_ACCESS_READ>{dctx, v});
201:   PETSC_NODISCARD static auto HostArrayWrite(PetscDeviceContext dctx, Vec v) noexcept PETSC_DECLTYPE_AUTO_RETURNS(VectorArray<PETSC_MEMTYPE_HOST, PETSC_MEMORY_ACCESS_WRITE>{dctx, v});
202:   PETSC_NODISCARD static auto HostArrayReadWrite(PetscDeviceContext dctx, Vec v) noexcept PETSC_DECLTYPE_AUTO_RETURNS(VectorArray<PETSC_MEMTYPE_HOST, PETSC_MEMORY_ACCESS_READ_WRITE>{dctx, v});

204:   // ops-table functions
205:   static PetscErrorCode Create(Vec) noexcept;
206:   static PetscErrorCode Destroy(Vec) noexcept;
207:   template <PetscMemType, PetscMemoryAccessMode, bool = false>
208:   static PetscErrorCode GetArray(Vec, PetscScalar **, PetscDeviceContext) noexcept;
209:   template <PetscMemType, PetscMemoryAccessMode, bool = false>
210:   static PetscErrorCode GetArray(Vec, PetscScalar **) noexcept;
211:   template <PetscMemType, PetscMemoryAccessMode>
212:   static PetscErrorCode RestoreArray(Vec, PetscScalar **, PetscDeviceContext) noexcept;
213:   template <PetscMemType, PetscMemoryAccessMode>
214:   static PetscErrorCode RestoreArray(Vec, PetscScalar **) noexcept;
215:   template <PetscMemoryAccessMode, bool = false>
216:   static PetscErrorCode GetArrayAndMemtype(Vec, PetscScalar **, PetscMemType *, PetscDeviceContext) noexcept;
217:   template <PetscMemoryAccessMode, bool = false>
218:   static PetscErrorCode GetArrayAndMemtype(Vec, PetscScalar **, PetscMemType *) noexcept;
219:   static PetscErrorCode GetArrayAndMemtypeAsync(Vec, PetscMemoryAccessMode, PetscScalar **, PetscMemType *) noexcept;
220:   template <PetscMemoryAccessMode>
221:   static PetscErrorCode RestoreArrayAndMemtype(Vec, PetscScalar **, PetscDeviceContext) noexcept;
222:   template <PetscMemoryAccessMode>
223:   static PetscErrorCode RestoreArrayAndMemtype(Vec, PetscScalar **) noexcept;
224:   template <PetscMemType>
225:   static PetscErrorCode ReplaceArray(Vec, const PetscScalar *) noexcept;
226:   template <PetscMemType>
227:   static PetscErrorCode ResetArray(Vec) noexcept;
228:   template <PetscMemType>
229:   static PetscErrorCode PlaceArray(Vec, const PetscScalar *) noexcept;

231:   // common ops shared between Seq and MPI
232:   static PetscErrorCode Create_CUPM(Vec) noexcept;
233:   static PetscErrorCode Create_CUPMBase(MPI_Comm, PetscInt, PetscInt, PetscInt, Vec *, PetscBool, PetscLayout /*reference*/ = nullptr) noexcept;
234:   static PetscErrorCode Initialize_CUPMBase(Vec, PetscBool, PetscScalar *, PetscScalar *, PetscDeviceContext) noexcept;
235:   template <typename SetupFunctionT = no_op>
236:   static PetscErrorCode Duplicate_CUPMBase(Vec, Vec *, PetscDeviceContext, SetupFunctionT && = SetupFunctionT{}) noexcept;
237:   static PetscErrorCode BindToCPU_CUPMBase(Vec, PetscBool, PetscDeviceContext) noexcept;
238:   static PetscErrorCode GetArrays_CUPMBase(Vec, const PetscScalar **, const PetscScalar **, PetscOffloadMask *, PetscDeviceContext) noexcept;
239:   static PetscErrorCode ResetPreallocationCOO_CUPMBase(Vec, PetscDeviceContext) noexcept;
240:   template <std::size_t NCount = 0, std::size_t NScal = 0>
241:   static PetscErrorCode SetPreallocationCOO_CUPMBase(Vec, PetscCount, const PetscInt[], PetscDeviceContext, const std::array<CooPair<PetscCount>, NCount> & = {}, const std::array<CooPair<PetscScalar>, NScal> & = {}) noexcept;

243:   static PetscErrorCode Convert_IMPL_IMPLCUPM(Vec) noexcept;
244: };

246: // ==========================================================================================
247: // Vec_CUPMBase::VectorArray
248: //
249: // RAII versions of the get/restore array routines. Determines constness of the pointer type,
250: // holds the pointer itself and provides the implicit conversion operator.
251: //
252: // On construction this calls the moral equivalent of Vec[CUPM]GetArray[Read|Write]()
253: // (depending on PetscMemoryAccessMode) and on destruction automatically restores the array
254: // for you
255: // ==========================================================================================
256: template <device::cupm::DeviceType T, typename D>
257: template <PetscMemType MT, PetscMemoryAccessMode MA>
258: class Vec_CUPMBase<T, D>::VectorArray : public device::cupm::impl::RestoreableArray<T, MT, MA> {
259:   using base_type = device::cupm::impl::RestoreableArray<T, MT, MA>;

261: public:
262:   VectorArray(PetscDeviceContext, Vec) noexcept;
263:   ~VectorArray() noexcept;

265: private:
266:   Vec v_ = nullptr;
267: };

269: // ==========================================================================================
270: // Vec_CUPMBase::VectorArray - Public API
271: // ==========================================================================================

273: template <device::cupm::DeviceType T, typename D>
274: template <PetscMemType MT, PetscMemoryAccessMode MA>
275: inline Vec_CUPMBase<T, D>::VectorArray<MT, MA>::VectorArray(PetscDeviceContext dctx, Vec v) noexcept : base_type{dctx}, v_{v}
276: {
277:   PetscFunctionBegin;
278:   PetscCallAbort(PETSC_COMM_SELF, Vec_CUPMBase<T, D>::template GetArray<MT, MA, true>(v, &this->ptr_, dctx));
279:   PetscFunctionReturnVoid();
280: }

282: template <device::cupm::DeviceType T, typename D>
283: template <PetscMemType MT, PetscMemoryAccessMode MA>
284: inline Vec_CUPMBase<T, D>::VectorArray<MT, MA>::~VectorArray() noexcept
285: {
286:   PetscFunctionBegin;
287:   PetscCallAbort(PETSC_COMM_SELF, Vec_CUPMBase<T, D>::template RestoreArray<MT, MA>(v_, &this->ptr_, this->dctx_));
288:   PetscFunctionReturnVoid();
289: }

291: // ==========================================================================================
292: // Vec_CUPMBase - Protected API
293: // ==========================================================================================

295: template <device::cupm::DeviceType T, typename D>
296: inline PetscErrorCode Vec_CUPMBase<T, D>::ResetAllocatedDevicePtr_(PetscDeviceContext dctx, Vec v, PetscScalar *new_value) noexcept
297: {
298:   auto &device_array = VecCUPMCast(v)->array_allocated_d;

300:   PetscFunctionBegin;
301:   if (device_array) {
302:     if (PetscDefined(HAVE_NVSHMEM) && VecCUPMCast(v)->nvshmem) {
303:       PetscCall(PetscNvshmemFree(device_array));
304:     } else {
305:       cupmStream_t stream;

307:       PetscCall(GetHandlesFrom_(dctx, &stream));
308:       PetscCallCUPM(cupmFreeAsync(device_array, stream));
309:     }
310:   }
311:   device_array = new_value;
312:   PetscFunctionReturn(PETSC_SUCCESS);
313: }

315: namespace
316: {

318: inline PetscErrorCode VecCUPMCheckMinimumPinnedMemory_Internal(Vec v, PetscBool *set = nullptr) noexcept
319: {
320:   auto      mem = static_cast<PetscInt>(v->minimum_bytes_pinned_memory);
321:   PetscBool flg;

323:   PetscFunctionBegin;
324:   PetscObjectOptionsBegin(PetscObjectCast(v));
325:   PetscCall(PetscOptionsRangeInt("-vec_pinned_memory_min", "Minimum size (in bytes) for an allocation to use pinned memory on host", "VecSetPinnedMemoryMin", mem, &mem, &flg, 0, std::numeric_limits<decltype(mem)>::max()));
326:   if (flg) v->minimum_bytes_pinned_memory = mem;
327:   PetscOptionsEnd();
328:   if (set) *set = flg;
329:   PetscFunctionReturn(PETSC_SUCCESS);
330: }

332: } // anonymous namespace

334: template <device::cupm::DeviceType T, typename D>
335: template <typename CastFunctionType>
336: inline PetscErrorCode Vec_CUPMBase<T, D>::VecAllocateCheck_(Vec v, void *&dest, CastFunctionType &&cast) noexcept
337: {
338:   PetscFunctionBegin;
339:   if (PetscLikely(dest)) PetscFunctionReturn(PETSC_SUCCESS);
340:   // do the check here so we don't have to do it in every function
341:   PetscCall(checkCupmBlasIntCast(v->map->n));
342:   {
343:     auto impl = cast(v);

345:     PetscCall(PetscNew(&impl));
346:     dest = impl;
347:   }
348:   PetscFunctionReturn(PETSC_SUCCESS);
349: }

351: template <device::cupm::DeviceType T, typename D>
352: inline PetscErrorCode Vec_CUPMBase<T, D>::VecIMPLAllocateCheck_(Vec v) noexcept
353: {
354:   PetscFunctionBegin;
355:   PetscCall(VecAllocateCheck_(v, v->data, VecIMPLCast<D>));
356:   PetscFunctionReturn(PETSC_SUCCESS);
357: }

359: // allocate the Vec_CUPM struct. this is normally done through DeviceAllocateCheck_(), but in
360: // certain circumstances (such as when the user places the device array) we do not want to do
361: // the full DeviceAllocateCheck_() as it also allocates the array
362: template <device::cupm::DeviceType T, typename D>
363: inline PetscErrorCode Vec_CUPMBase<T, D>::VecCUPMAllocateCheck_(Vec v) noexcept
364: {
365:   PetscFunctionBegin;
366:   if (!v->spptr) {
367:     /*
368:       This is where v first gets a CUPM device array, which only the CUPM vector types use. If v is
369:       any other type, such as VECSEQ, its operations ignore that array, so any result a device
370:       routine writes there is silently lost. PetscCheckTypeNames() catches this only in debug
371:       builds, so check the type here too. The check runs only once per vector, on the first
372:       allocation.
373:     */
374:     PetscBool iscupm;

376:     PetscCall(PetscObjectTypeCompareAny(PetscObjectCast(v), &iscupm, VECSEQCUPM(), VECMPICUPM(), ""));
377:     PetscCheck(iscupm, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Vec type %s cannot hold a device array, it must be %s or %s. Obtain vectors for a device operation from MatCreateVecs(), or set their type with VecSetType()", PetscObjectCast(v)->type_name, VECSEQCUPM(), VECMPICUPM());
378:   }
379:   PetscCall(VecAllocateCheck_(v, v->spptr, VecCUPMCast));
380:   PetscFunctionReturn(PETSC_SUCCESS);
381: }

383: template <device::cupm::DeviceType T, typename D>
384: inline PetscErrorCode Vec_CUPMBase<T, D>::HostAllocateCheck_(PetscDeviceContext, Vec v) noexcept
385: {
386:   PetscFunctionBegin;
387:   PetscCall(VecIMPLAllocateCheck_(v));
388:   if (auto &alloc = VecIMPLCast(v)->array_allocated) PetscFunctionReturn(PETSC_SUCCESS);
389:   else {
390:     PetscCall(VecCUPMCheckMinimumPinnedMemory_Internal(v));
391:     {
392:       const auto n     = v->map->n;
393:       const auto useit = UseCUPMHostAlloc((n * sizeof(*alloc)) > v->minimum_bytes_pinned_memory);

395:       v->pinned_memory = static_cast<decltype(v->pinned_memory)>(useit.value());
396:       PetscCall(PetscMalloc1(n, &alloc));
397:     }
398:     if (!VecIMPLCast(v)->array) VecIMPLCast(v)->array = alloc;
399:     if (v->offloadmask == PETSC_OFFLOAD_UNALLOCATED) v->offloadmask = PETSC_OFFLOAD_CPU;
400:   }
401:   PetscFunctionReturn(PETSC_SUCCESS);
402: }

404: template <device::cupm::DeviceType T, typename D>
405: inline PetscErrorCode Vec_CUPMBase<T, D>::DeviceAllocateCheck_(PetscDeviceContext dctx, Vec v) noexcept
406: {
407:   PetscFunctionBegin;
408:   PetscCall(VecCUPMAllocateCheck_(v));
409:   if (auto &alloc = VecCUPMCast(v)->array_d) PetscFunctionReturn(PETSC_SUCCESS);
410:   else {
411:     const auto   n                 = v->map->n;
412:     auto        &array_allocated_d = VecCUPMCast(v)->array_allocated_d;
413:     cupmStream_t stream;

415:     PetscCall(GetHandlesFrom_(dctx, &stream));
416:     PetscCall(PetscCUPMMallocAsync(&array_allocated_d, n, stream));
417:     alloc = array_allocated_d;
418:     if (v->offloadmask == PETSC_OFFLOAD_UNALLOCATED) {
419:       const auto vimp = VecIMPLCast(v);
420:       v->offloadmask  = (vimp && vimp->array) ? PETSC_OFFLOAD_CPU : PETSC_OFFLOAD_GPU;
421:     }
422:   }
423:   PetscFunctionReturn(PETSC_SUCCESS);
424: }

426: template <device::cupm::DeviceType T, typename D>
427: inline PetscErrorCode Vec_CUPMBase<T, D>::CopyToDevice_(PetscDeviceContext dctx, Vec v, bool forceasync) noexcept
428: {
429:   PetscFunctionBegin;
430:   PetscCall(DeviceAllocateCheck_(dctx, v));
431:   if (v->offloadmask == PETSC_OFFLOAD_CPU) {
432:     cupmStream_t stream;

434:     v->offloadmask = PETSC_OFFLOAD_BOTH;
435:     PetscCall(GetHandlesFrom_(dctx, &stream));
436:     PetscCall(PetscLogEventBegin(VEC_CUPMCopyToGPU(), v, 0, 0, 0));
437:     PetscCall(PetscCUPMMemcpyAsync(VecCUPMCast(v)->array_d, VecIMPLCast(v)->array, v->map->n, cupmMemcpyHostToDevice, stream, forceasync));
438:     PetscCall(PetscLogEventEnd(VEC_CUPMCopyToGPU(), v, 0, 0, 0));
439:   }
440:   PetscFunctionReturn(PETSC_SUCCESS);
441: }

443: template <device::cupm::DeviceType T, typename D>
444: inline PetscErrorCode Vec_CUPMBase<T, D>::CopyToHost_(PetscDeviceContext dctx, Vec v, bool forceasync) noexcept
445: {
446:   PetscFunctionBegin;
447:   PetscCall(HostAllocateCheck_(dctx, v));
448:   if (v->offloadmask == PETSC_OFFLOAD_GPU) {
449:     cupmStream_t stream;

451:     v->offloadmask = PETSC_OFFLOAD_BOTH;
452:     PetscCall(GetHandlesFrom_(dctx, &stream));
453:     PetscCall(PetscLogEventBegin(VEC_CUPMCopyFromGPU(), v, 0, 0, 0));
454:     PetscCall(PetscCUPMMemcpyAsync(VecIMPLCast(v)->array, VecCUPMCast(v)->array_d, v->map->n, cupmMemcpyDeviceToHost, stream, forceasync));
455:     PetscCall(PetscLogEventEnd(VEC_CUPMCopyFromGPU(), v, 0, 0, 0));
456:   }
457:   PetscFunctionReturn(PETSC_SUCCESS);
458: }

460: template <device::cupm::DeviceType T, typename D>
461: inline PetscErrorCode Vec_CUPMBase<T, D>::DestroyDevice_(Vec v) noexcept
462: {
463:   PetscFunctionBegin;
464:   if (const auto vcu = VecCUPMCast(v)) {
465:     PetscDeviceContext dctx;

467:     PetscCall(GetHandles_(&dctx));
468:     PetscCall(ResetAllocatedDevicePtr_(dctx, v));
469:     PetscCall(ResetPreallocationCOO_CUPMBase(v, dctx));
470:     PetscCall(PetscFree(v->spptr));
471:   }
472:   PetscFunctionReturn(PETSC_SUCCESS);
473: }

475: template <device::cupm::DeviceType T, typename D>
476: inline PetscErrorCode Vec_CUPMBase<T, D>::DestroyHost_(Vec v) noexcept
477: {
478:   PetscFunctionBegin;
479:   PetscCall(PetscObjectSAWsViewOff(PetscObjectCast(v)));
480:   if (const auto vimpl = VecIMPLCast(v)) {
481:     if (auto &array_allocated = vimpl->array_allocated) {
482:       const auto useit = UseCUPMHostAlloc(v->pinned_memory);

484:       // do this ourselves since we may want to use the cupm functions
485:       PetscCall(PetscFree(array_allocated));
486:     }
487:   }
488:   v->pinned_memory = PETSC_FALSE;
489:   PetscCall(VecDestroy_IMPL(v));
490:   PetscFunctionReturn(PETSC_SUCCESS);
491: }

493: // ==========================================================================================
494: // Vec_CUPMBase - Public API
495: // ==========================================================================================

497: template <device::cupm::DeviceType T, typename D>
498: inline typename Vec_CUPMBase<T, D>::Vec_CUPM *Vec_CUPMBase<T, D>::VecCUPMCast(Vec v) noexcept
499: {
500:   return static_cast<Vec_CUPM *>(v->spptr);
501: }

503: // This is a trick to get around the fact that in CRTP the derived class is not yet fully
504: // defined because Base must necessarily be instantiated before Derived is
505: // complete. By using a dummy template parameter we make the type "dependent" and so will
506: // only be determined when the derived class is instantiated (and therefore fully defined)
507: template <device::cupm::DeviceType T, typename D>
508: template <typename U>
509: inline constexpr auto Vec_CUPMBase<T, D>::VecIMPLCast(Vec v) noexcept -> decltype(U::VecIMPLCast_(v))
510: {
511:   return U::VecIMPLCast_(v);
512: }

514: template <device::cupm::DeviceType T, typename D>
515: inline PetscErrorCode Vec_CUPMBase<T, D>::VecDestroy_IMPL(Vec v) noexcept
516: {
517:   return D::VecDestroy_IMPL_(v);
518: }

520: template <device::cupm::DeviceType T, typename D>
521: inline PetscErrorCode Vec_CUPMBase<T, D>::VecResetArray_IMPL(Vec v) noexcept
522: {
523:   return D::VecResetArray_IMPL_(v);
524: }

526: template <device::cupm::DeviceType T, typename D>
527: inline PetscErrorCode Vec_CUPMBase<T, D>::VecPlaceArray_IMPL(Vec v, const PetscScalar *a) noexcept
528: {
529:   return D::VecPlaceArray_IMPL_(v, a);
530: }

532: template <device::cupm::DeviceType T, typename D>
533: inline PetscErrorCode Vec_CUPMBase<T, D>::VecCreate_IMPL_Private(Vec v, PetscBool *alloc_missing, PetscInt nghost, PetscScalar *host_array) noexcept
534: {
535:   return D::VecCreate_IMPL_Private_(v, alloc_missing, nghost, host_array);
536: }

538: template <device::cupm::DeviceType T, typename D>
539: inline constexpr PetscLogEvent Vec_CUPMBase<T, D>::VEC_CUPMCopyToGPU() noexcept
540: {
541:   return T == device::cupm::DeviceType::CUDA ? VEC_CUDACopyToGPU : VEC_HIPCopyToGPU;
542: }

544: template <device::cupm::DeviceType T, typename D>
545: inline constexpr PetscLogEvent Vec_CUPMBase<T, D>::VEC_CUPMCopyFromGPU() noexcept
546: {
547:   return T == device::cupm::DeviceType::CUDA ? VEC_CUDACopyFromGPU : VEC_HIPCopyFromGPU;
548: }

550: template <device::cupm::DeviceType T, typename D>
551: inline constexpr VecType Vec_CUPMBase<T, D>::VECSEQCUPM() noexcept
552: {
553:   return T == device::cupm::DeviceType::CUDA ? VECSEQCUDA : VECSEQHIP;
554: }

556: template <device::cupm::DeviceType T, typename D>
557: inline constexpr VecType Vec_CUPMBase<T, D>::VECMPICUPM() noexcept
558: {
559:   return T == device::cupm::DeviceType::CUDA ? VECMPICUDA : VECMPIHIP;
560: }

562: template <device::cupm::DeviceType T, typename D>
563: inline constexpr VecType Vec_CUPMBase<T, D>::VECCUPM() noexcept
564: {
565:   return T == device::cupm::DeviceType::CUDA ? VECCUDA : VECHIP;
566: }

568: template <device::cupm::DeviceType T, typename D>
569: template <typename U>
570: inline constexpr VecType Vec_CUPMBase<T, D>::VECIMPLCUPM() noexcept
571: {
572:   return U::VECIMPLCUPM_();
573: }

575: template <device::cupm::DeviceType T, typename D>
576: template <typename U>
577: inline constexpr VecType Vec_CUPMBase<T, D>::VECIMPL() noexcept
578: {
579:   return U::VECIMPL_();
580: }

582: // private version that takes a PetscDeviceContext, called by the public variant
583: template <device::cupm::DeviceType T, typename D>
584: template <PetscMemType mtype, PetscMemoryAccessMode access, bool force>
585: inline PetscErrorCode Vec_CUPMBase<T, D>::GetArray(Vec v, PetscScalar **a, PetscDeviceContext dctx) noexcept
586: {
587:   constexpr auto hostmem     = PetscMemTypeHost(mtype);
588:   const auto     oldmask     = v->offloadmask;
589:   auto          &mask        = v->offloadmask;
590:   auto           should_sync = false;

592:   PetscFunctionBegin;
593:   static_assert((mtype == PETSC_MEMTYPE_HOST) || (mtype == PETSC_MEMTYPE_DEVICE), "");
594:   PetscCheckTypeNames(v, VECSEQCUPM(), VECMPICUPM());
595:   if (PetscMemoryAccessRead(access)) {
596:     // READ or READ_WRITE
597:     if ((oldmask == PETSC_OFFLOAD_GPU && hostmem) || (oldmask == PETSC_OFFLOAD_CPU && !hostmem)) {
598:       // if we move the data we should set the flag to synchronize later on
599:       should_sync = true;
600:     }
601:     PetscCall((hostmem ? CopyToHost_ : CopyToDevice_)(dctx, v, force));
602:   } else {
603:     // WRITE only
604:     PetscCall((hostmem ? HostAllocateCheck_ : DeviceAllocateCheck_)(dctx, v));
605:   }
606:   *a = hostmem ? VecIMPLCast(v)->array : VecCUPMCast(v)->array_d;
607:   // if unallocated previously we should zero things out if we intend to read
608:   if (PetscMemoryAccessRead(access) && (oldmask == PETSC_OFFLOAD_UNALLOCATED)) {
609:     const auto n = v->map->n;

611:     if (hostmem) {
612:       PetscCall(PetscArrayzero(*a, n));
613:     } else {
614:       cupmStream_t stream;

616:       PetscCall(GetHandlesFrom_(dctx, &stream));
617:       PetscCall(PetscCUPMMemsetAsync(*a, 0, n, stream, force));
618:       should_sync = true;
619:     }
620:   }
621:   // update the offloadmask if we intend to write, since we assume immediately modified
622:   if (PetscMemoryAccessWrite(access)) {
623:     PetscCall(VecSetErrorIfLocked(v, 1));
624:     // REVIEW ME: this should probably also call PetscObjectStateIncrease() since we assume it
625:     // is immediately modified
626:     mask = hostmem ? PETSC_OFFLOAD_CPU : PETSC_OFFLOAD_GPU;
627:   }
628:   // if we are a globally blocking stream and we have MOVED data then we should synchronize,
629:   // since even doing async calls on the NULL stream is not synchronous
630:   if (!force && should_sync) PetscCall(PetscDeviceContextSynchronize(dctx));
631:   PetscFunctionReturn(PETSC_SUCCESS);
632: }

634: // v->ops->getarray[read|write] or VecCUPMGetArray[Read|Write]()
635: template <device::cupm::DeviceType T, typename D>
636: template <PetscMemType mtype, PetscMemoryAccessMode access, bool force>
637: inline PetscErrorCode Vec_CUPMBase<T, D>::GetArray(Vec v, PetscScalar **a) noexcept
638: {
639:   PetscDeviceContext dctx;

641:   PetscFunctionBegin;
642:   PetscCall(GetHandles_(&dctx));
643:   PetscCall(D::template GetArray<mtype, access, force>(v, a, dctx));
644:   PetscFunctionReturn(PETSC_SUCCESS);
645: }

647: // private version that takes a PetscDeviceContext, called by the public variant
648: template <device::cupm::DeviceType T, typename D>
649: template <PetscMemType mtype, PetscMemoryAccessMode access>
650: inline PetscErrorCode Vec_CUPMBase<T, D>::RestoreArray(Vec v, PetscScalar **a, PetscDeviceContext) noexcept
651: {
652:   PetscFunctionBegin;
653:   static_assert((mtype == PETSC_MEMTYPE_HOST) || (mtype == PETSC_MEMTYPE_DEVICE), "");
654:   PetscCheckTypeNames(v, VECSEQCUPM(), VECMPICUPM());
655:   if (PetscMemoryAccessWrite(access)) {
656:     // WRITE or READ_WRITE
657:     PetscCall(PetscObjectStateIncrease(PetscObjectCast(v)));
658:     v->offloadmask = PetscMemTypeHost(mtype) ? PETSC_OFFLOAD_CPU : PETSC_OFFLOAD_GPU;
659:   }
660:   if (a) {
661:     PetscCall(CheckPointerMatchesMemType_(*a, mtype));
662:     *a = nullptr;
663:   }
664:   PetscFunctionReturn(PETSC_SUCCESS);
665: }

667: // v->ops->restorearray[read|write] or VecCUPMRestoreArray[Read|Write]()
668: template <device::cupm::DeviceType T, typename D>
669: template <PetscMemType mtype, PetscMemoryAccessMode access>
670: inline PetscErrorCode Vec_CUPMBase<T, D>::RestoreArray(Vec v, PetscScalar **a) noexcept
671: {
672:   PetscDeviceContext dctx;

674:   PetscFunctionBegin;
675:   PetscCall(GetHandles_(&dctx));
676:   PetscCall(D::template RestoreArray<mtype, access>(v, a, dctx));
677:   PetscFunctionReturn(PETSC_SUCCESS);
678: }

680: template <device::cupm::DeviceType T, typename D>
681: template <PetscMemoryAccessMode access, bool force>
682: inline PetscErrorCode Vec_CUPMBase<T, D>::GetArrayAndMemtype(Vec v, PetscScalar **a, PetscMemType *mtype, PetscDeviceContext dctx) noexcept
683: {
684:   PetscFunctionBegin;
685:   if (a) PetscCall(D::template GetArray<PETSC_MEMTYPE_DEVICE, access, force>(v, a, dctx));
686:   if (mtype) *mtype = (PetscDefined(HAVE_NVSHMEM) && VecCUPMCast(v)->nvshmem) ? PETSC_MEMTYPE_NVSHMEM : PETSC_MEMTYPE_CUPM();
687:   PetscFunctionReturn(PETSC_SUCCESS);
688: }

690: // v->ops->getarrayandmemtype
691: template <device::cupm::DeviceType T, typename D>
692: template <PetscMemoryAccessMode access, bool force>
693: inline PetscErrorCode Vec_CUPMBase<T, D>::GetArrayAndMemtype(Vec v, PetscScalar **a, PetscMemType *mtype) noexcept
694: {
695:   PetscDeviceContext dctx;

697:   PetscFunctionBegin;
698:   PetscCall(GetHandles_(&dctx));
699:   PetscCall(D::template GetArrayAndMemtype<access, force>(v, a, mtype, dctx));
700:   PetscFunctionReturn(PETSC_SUCCESS);
701: }

703: template <device::cupm::DeviceType T, typename D>
704: inline PetscErrorCode Vec_CUPMBase<T, D>::GetArrayAndMemtypeAsync(Vec v, PetscMemoryAccessMode access, PetscScalar **a, PetscMemType *mtype) noexcept
705: {
706:   PetscFunctionBegin;
707:   switch (access) {
708:   case PETSC_MEMORY_ACCESS_READ:
709:     PetscCall(D::template GetArrayAndMemtype<PETSC_MEMORY_ACCESS_READ, true>(v, a, mtype));
710:     break;
711:   case PETSC_MEMORY_ACCESS_WRITE:
712:     PetscCall(D::template GetArrayAndMemtype<PETSC_MEMORY_ACCESS_WRITE, true>(v, a, mtype));
713:     break;
714:   case PETSC_MEMORY_ACCESS_READ_WRITE:
715:     PetscCall(D::template GetArrayAndMemtype<PETSC_MEMORY_ACCESS_READ_WRITE, true>(v, a, mtype));
716:     break;
717:   default:
718:     SETERRQ(PetscObjectComm(PetscObjectCast(v)), PETSC_ERR_ARG_OUTOFRANGE, "Invalid memory access mode %d", (int)access);
719:   }
720:   PetscFunctionReturn(PETSC_SUCCESS);
721: }

723: template <device::cupm::DeviceType T, typename D>
724: template <PetscMemoryAccessMode access>
725: inline PetscErrorCode Vec_CUPMBase<T, D>::RestoreArrayAndMemtype(Vec v, PetscScalar **a, PetscDeviceContext dctx) noexcept
726: {
727:   PetscFunctionBegin;
728:   PetscCall(D::template RestoreArray<PETSC_MEMTYPE_DEVICE, access>(v, a, dctx));
729:   PetscFunctionReturn(PETSC_SUCCESS);
730: }

732: // v->ops->restorearrayandmemtype
733: template <device::cupm::DeviceType T, typename D>
734: template <PetscMemoryAccessMode access>
735: inline PetscErrorCode Vec_CUPMBase<T, D>::RestoreArrayAndMemtype(Vec v, PetscScalar **a) noexcept
736: {
737:   PetscDeviceContext dctx;

739:   PetscFunctionBegin;
740:   PetscCall(GetHandles_(&dctx));
741:   PetscCall(D::template RestoreArrayAndMemtype<access>(v, a, dctx));
742:   PetscFunctionReturn(PETSC_SUCCESS);
743: }

745: // v->ops->placearray or VecCUPMPlaceArray()
746: template <device::cupm::DeviceType T, typename D>
747: template <PetscMemType mtype>
748: inline PetscErrorCode Vec_CUPMBase<T, D>::PlaceArray(Vec v, const PetscScalar *a) noexcept
749: {
750:   PetscDeviceContext dctx;

752:   PetscFunctionBegin;
753:   static_assert((mtype == PETSC_MEMTYPE_HOST) || (mtype == PETSC_MEMTYPE_DEVICE), "");
754:   PetscCheckTypeNames(v, VECSEQCUPM(), VECMPICUPM());
755:   PetscCall(CheckPointerMatchesMemType_(a, mtype));
756:   PetscCall(GetHandles_(&dctx));
757:   if (PetscMemTypeHost(mtype)) {
758:     PetscCall(CopyToHost_(dctx, v));
759:     PetscCall(VecPlaceArray_IMPL(v, a));
760:     v->offloadmask = PETSC_OFFLOAD_CPU;
761:   } else {
762:     PetscCall(VecIMPLAllocateCheck_(v));
763:     {
764:       auto &backup_array = VecIMPLCast(v)->unplacedarray;

766:       PetscCheck(!backup_array, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "VecPlaceArray() was already called on this vector, without a call to VecResetArray()");
767:       PetscCall(CopyToDevice_(dctx, v));
768:       PetscCall(PetscObjectStateIncrease(PetscObjectCast(v)));
769:       backup_array = util::exchange(VecCUPMCast(v)->array_d, const_cast<PetscScalar *>(a));
770:       // only update the offload mask if we actually assign a pointer
771:       if (a) v->offloadmask = PETSC_OFFLOAD_GPU;
772:     }
773:   }
774:   PetscFunctionReturn(PETSC_SUCCESS);
775: }

777: // v->ops->replacearray or VecCUPMReplaceArray()
778: template <device::cupm::DeviceType T, typename D>
779: template <PetscMemType mtype>
780: inline PetscErrorCode Vec_CUPMBase<T, D>::ReplaceArray(Vec v, const PetscScalar *a) noexcept
781: {
782:   const auto         aptr = const_cast<PetscScalar *>(a);
783:   PetscDeviceContext dctx;

785:   PetscFunctionBegin;
786:   static_assert((mtype == PETSC_MEMTYPE_HOST) || (mtype == PETSC_MEMTYPE_DEVICE), "");
787:   PetscCheckTypeNames(v, VECSEQCUPM(), VECMPICUPM());
788:   PetscCall(CheckPointerMatchesMemType_(a, mtype));
789:   PetscCall(GetHandles_(&dctx));
790:   if (PetscMemTypeHost(mtype)) {
791:     PetscCall(VecIMPLAllocateCheck_(v));
792:     {
793:       const auto vimpl      = VecIMPLCast(v);
794:       auto      &host_array = vimpl->array_allocated;

796:       // Preserve caller-owned storage; PETSc-owned storage below is discarded.
797:       if (host_array != vimpl->array) {
798:         PetscCall(CopyToHost_(dctx, v));
799:         PetscCall(PetscDeviceContextSynchronize(dctx));
800:       }
801:       if (host_array) {
802:         const auto useit = UseCUPMHostAlloc(v->pinned_memory);

804:         PetscCall(PetscFree(host_array));
805:       }
806:       host_array       = aptr;
807:       vimpl->array     = host_array;
808:       v->pinned_memory = PETSC_FALSE; // REVIEW ME: we can determine this
809:       v->offloadmask   = PETSC_OFFLOAD_CPU;
810:     }
811:   } else {
812:     PetscCall(VecCUPMAllocateCheck_(v));
813:     {
814:       const auto vcu = VecCUPMCast(v);

816:       PetscCall(ResetAllocatedDevicePtr_(dctx, v, aptr));
817:       // don't update the offloadmask if placed pointer is NULL
818:       vcu->array_d = vcu->array_allocated_d /* = aptr */;
819:       if (aptr) v->offloadmask = PETSC_OFFLOAD_GPU;
820:     }
821:   }
822:   PetscCall(PetscObjectStateIncrease(PetscObjectCast(v)));
823:   PetscFunctionReturn(PETSC_SUCCESS);
824: }

826: // v->ops->resetarray or VecCUPMResetArray()
827: template <device::cupm::DeviceType T, typename D>
828: template <PetscMemType mtype>
829: inline PetscErrorCode Vec_CUPMBase<T, D>::ResetArray(Vec v) noexcept
830: {
831:   PetscDeviceContext dctx;

833:   PetscFunctionBegin;
834:   static_assert((mtype == PETSC_MEMTYPE_HOST) || (mtype == PETSC_MEMTYPE_DEVICE), "");
835:   PetscCheckTypeNames(v, VECSEQCUPM(), VECMPICUPM());
836:   PetscCall(GetHandles_(&dctx));
837:   // REVIEW ME:
838:   // this is wildly inefficient but must be done if we assume that the placed array must have
839:   // correct values
840:   if (PetscMemTypeHost(mtype)) {
841:     PetscCall(CopyToHost_(dctx, v));
842:     PetscCall(VecResetArray_IMPL(v));
843:     v->offloadmask = PETSC_OFFLOAD_CPU;
844:     // A previous upload may still read the array even when no copy-back was needed.
845:     PetscCall(PetscDeviceContextSynchronize(dctx));
846:   } else {
847:     PetscCall(VecIMPLAllocateCheck_(v));
848:     PetscCall(VecCUPMAllocateCheck_(v));
849:     {
850:       const auto vcu        = VecCUPMCast(v);
851:       const auto vimpl      = VecIMPLCast(v);
852:       auto      &host_array = vimpl->unplacedarray;

854:       PetscCall(CheckPointerMatchesMemType_(host_array, PETSC_MEMTYPE_DEVICE));
855:       if (v->offloadmask == PETSC_OFFLOAD_CPU) {
856:         PetscCall(CopyToDevice_(dctx, v));
857:         PetscCall(PetscDeviceContextSynchronize(dctx)); // Above H2D might be async, so we must sync dctx, otherwise if later user writes v's host array, it could ruin the H2D
858:       }
859:       PetscCall(PetscObjectStateIncrease(PetscObjectCast(v)));
860:       // Need to reset the offloadmask. If we had a stashed pointer we are on the GPU,
861:       // otherwise check if the host has a valid pointer. If neither, then we are not
862:       // allocated.
863:       vcu->array_d = host_array;
864:       if (host_array) {
865:         host_array     = nullptr;
866:         v->offloadmask = PETSC_OFFLOAD_GPU;
867:       } else if (vimpl->array) {
868:         v->offloadmask = PETSC_OFFLOAD_CPU;
869:       } else {
870:         v->offloadmask = PETSC_OFFLOAD_UNALLOCATED;
871:       }
872:     }
873:   }
874:   PetscFunctionReturn(PETSC_SUCCESS);
875: }

877: // v->ops->create
878: template <device::cupm::DeviceType T, typename D>
879: inline PetscErrorCode Vec_CUPMBase<T, D>::Create(Vec v) noexcept
880: {
881:   PetscBool          alloc_missing;
882:   PetscDeviceContext dctx;

884:   PetscFunctionBegin;
885:   PetscCall(VecCreate_IMPL_Private(v, &alloc_missing));
886:   PetscCall(GetHandles_(&dctx));
887:   PetscCall(Initialize_CUPMBase(v, alloc_missing, nullptr, nullptr, dctx));
888:   PetscFunctionReturn(PETSC_SUCCESS);
889: }

891: // v->ops->destroy
892: template <device::cupm::DeviceType T, typename D>
893: inline PetscErrorCode Vec_CUPMBase<T, D>::Destroy(Vec v) noexcept
894: {
895:   PetscFunctionBegin;
896:   PetscCall(DestroyDevice_(v));
897:   PetscCall(DestroyHost_(v));
898:   PetscFunctionReturn(PETSC_SUCCESS);
899: }

901: // ================================================================================== //
902: //                      Common core between Seq and MPI                               //

904: // VecCreate_CUPM()
905: template <device::cupm::DeviceType T, typename D>
906: inline PetscErrorCode Vec_CUPMBase<T, D>::Create_CUPM(Vec v) noexcept
907: {
908:   PetscMPIInt size;

910:   PetscFunctionBegin;
911:   PetscCallMPI(MPI_Comm_size(PetscObjectComm(PetscObjectCast(v)), &size));
912:   PetscCall(VecSetType(v, size > 1 ? VECMPICUPM() : VECSEQCUPM()));
913:   PetscFunctionReturn(PETSC_SUCCESS);
914: }

916: // VecCreateCUPM()
917: template <device::cupm::DeviceType T, typename D>
918: inline PetscErrorCode Vec_CUPMBase<T, D>::Create_CUPMBase(MPI_Comm comm, PetscInt bs, PetscInt n, PetscInt N, Vec *v, PetscBool call_set_type, PetscLayout reference) noexcept
919: {
920:   PetscFunctionBegin;
921:   PetscCall(VecCreate(comm, v));
922:   if (reference) PetscCall(PetscLayoutReference(reference, &(*v)->map));
923:   PetscCall(VecSetSizes(*v, n, N));
924:   if (bs) PetscCall(VecSetBlockSize(*v, bs));
925:   if (call_set_type) PetscCall(VecSetType(*v, VECIMPLCUPM()));
926:   PetscFunctionReturn(PETSC_SUCCESS);
927: }

929: // VecCreateIMPL_CUPM(), called through v->ops->create
930: template <device::cupm::DeviceType T, typename D>
931: inline PetscErrorCode Vec_CUPMBase<T, D>::Initialize_CUPMBase(Vec v, PetscBool allocate_missing, PetscScalar *host_array, PetscScalar *device_array, PetscDeviceContext dctx) noexcept
932: {
933:   PetscFunctionBegin;
934:   // REVIEW ME: perhaps not needed
935:   PetscCall(PetscDeviceInitialize(PETSC_DEVICE_CUPM()));
936:   PetscCall(PetscObjectChangeTypeName(PetscObjectCast(v), VECIMPLCUPM()));
937:   PetscCall(D::BindToCPU(v, PETSC_FALSE));
938:   if (device_array) {
939:     PetscCall(CheckPointerMatchesMemType_(device_array, PETSC_MEMTYPE_CUPM()));
940:     PetscCall(VecCUPMAllocateCheck_(v));
941:     VecCUPMCast(v)->array_d = device_array;
942:   }
943:   if (host_array) {
944:     PetscCall(CheckPointerMatchesMemType_(host_array, PETSC_MEMTYPE_HOST));
945:     VecIMPLCast(v)->array = host_array;
946:   }
947:   if (allocate_missing) {
948:     PetscCall(DeviceAllocateCheck_(dctx, v));
949:     PetscCall(HostAllocateCheck_(dctx, v));
950:     // REVIEW ME: junchao, is this needed with new calloc() branch? VecSet() will call
951:     // set() for reference
952:     // calls device-version
953:     PetscCall(VecSet(v, 0));
954:     // zero the host while device is underway
955:     PetscCall(PetscArrayzero(VecIMPLCast(v)->array, v->map->n));
956:     v->offloadmask = PETSC_OFFLOAD_BOTH;
957:   } else {
958:     if (host_array) {
959:       v->offloadmask = device_array ? PETSC_OFFLOAD_BOTH : PETSC_OFFLOAD_CPU;
960:     } else {
961:       v->offloadmask = device_array ? PETSC_OFFLOAD_GPU : PETSC_OFFLOAD_UNALLOCATED;
962:     }
963:   }
964:   PetscFunctionReturn(PETSC_SUCCESS);
965: }

967: // v->ops->duplicate
968: template <device::cupm::DeviceType T, typename D>
969: template <typename SetupFunctionT>
970: inline PetscErrorCode Vec_CUPMBase<T, D>::Duplicate_CUPMBase(Vec v, Vec *y, PetscDeviceContext dctx, SetupFunctionT &&DerivedCreateIMPLCUPM_Async) noexcept
971: {
972:   // if the derived setup is the default no_op then we should call VecSetType()
973:   constexpr auto call_set_type = static_cast<PetscBool>(std::is_same<SetupFunctionT, no_op>::value);
974:   const auto     vobj          = PetscObjectCast(v);
975:   const auto     map           = v->map;
976:   PetscInt       bs;

978:   PetscFunctionBegin;
979:   PetscCall(VecGetBlockSize(v, &bs));
980:   PetscCall(Create_CUPMBase(PetscObjectComm(vobj), bs, map->n, map->N, y, call_set_type, map));
981:   // Derived class can set up the remainder of the data structures here
982:   PetscCall(DerivedCreateIMPLCUPM_Async(*y));
983:   // If the other vector is bound to CPU then the memcpy of the ops struct will give the
984:   // duplicated vector the host "getarray" function which does not lazily allocate the array
985:   // (as it is assumed to always exist). So we force allocation here, before we overwrite the
986:   // ops
987:   if (v->boundtocpu) PetscCall(HostAllocateCheck_(dctx, *y));
988:   // in case the user has done some VecSetOps() tomfoolery
989:   (*y)->ops[0] = v->ops[0];
990:   {
991:     const auto yobj = PetscObjectCast(*y);

993:     PetscCall(PetscObjectListDuplicate(vobj->olist, &yobj->olist));
994:     PetscCall(PetscFunctionListDuplicate(vobj->qlist, &yobj->qlist));
995:   }
996:   (*y)->stash.donotstash   = v->stash.donotstash;
997:   (*y)->stash.ignorenegidx = v->stash.ignorenegidx;
998:   (*y)->map->bs            = std::abs(v->map->bs);
999:   (*y)->bstash.bs          = v->bstash.bs;
1000:   PetscFunctionReturn(PETSC_SUCCESS);
1001: }

1003:   #define VecSetOp_CUPM(op_name, op_host, ...) \
1004:     do { \
1005:       if (usehost) { \
1006:         v->ops->op_name = op_host; \
1007:       } else { \
1008:         v->ops->op_name = __VA_ARGS__; \
1009:       } \
1010:     } while (0)

1012: // v->ops->bindtocpu
1013: template <device::cupm::DeviceType T, typename D>
1014: inline PetscErrorCode Vec_CUPMBase<T, D>::BindToCPU_CUPMBase(Vec v, PetscBool usehost, PetscDeviceContext dctx) noexcept
1015: {
1016:   PetscFunctionBegin;
1017:   v->boundtocpu = usehost;
1018:   if (usehost) PetscCall(CopyToHost_(dctx, v));
1019:   PetscCall(PetscStrFreeAllocpy(usehost ? PETSCRANDER48 : PETSCDEVICERAND(), &v->defaultrandtype));

1021:   // set the base functions that are guaranteed to be the same for both
1022:   v->ops->duplicate = D::Duplicate;
1023:   v->ops->create    = D::Create;
1024:   v->ops->destroy   = D::Destroy;
1025:   v->ops->bindtocpu = D::BindToCPU;
1026:   // Note that setting these to NULL on host breaks convergence in certain areas. I don't know
1027:   // why, and I don't know how, but it is IMPERATIVE these are set as such!
1028:   v->ops->replacearray = D::template ReplaceArray<PETSC_MEMTYPE_HOST>;
1029:   v->ops->restorearray = D::template RestoreArray<PETSC_MEMTYPE_HOST, PETSC_MEMORY_ACCESS_READ_WRITE>;

1031:   // set device-only common functions
1032:   VecSetOp_CUPM(getarray, nullptr, D::template GetArray<PETSC_MEMTYPE_HOST, PETSC_MEMORY_ACCESS_READ_WRITE>);
1033:   VecSetOp_CUPM(getarraywrite, nullptr, D::template GetArray<PETSC_MEMTYPE_HOST, PETSC_MEMORY_ACCESS_WRITE>);
1034:   VecSetOp_CUPM(restorearraywrite, nullptr, D::template RestoreArray<PETSC_MEMTYPE_HOST, PETSC_MEMORY_ACCESS_WRITE>);

1036:   VecSetOp_CUPM(getarrayread, nullptr, [](Vec v, const PetscScalar **a) { return D::template GetArray<PETSC_MEMTYPE_HOST, PETSC_MEMORY_ACCESS_READ>(v, const_cast<PetscScalar **>(a)); });
1037:   VecSetOp_CUPM(restorearrayread, nullptr, [](Vec v, const PetscScalar **a) { return D::template RestoreArray<PETSC_MEMTYPE_HOST, PETSC_MEMORY_ACCESS_READ>(v, const_cast<PetscScalar **>(a)); });

1039:   VecSetOp_CUPM(getarrayandmemtype, nullptr, D::template GetArrayAndMemtype<PETSC_MEMORY_ACCESS_READ_WRITE>);
1040:   VecSetOp_CUPM(restorearrayandmemtype, nullptr, D::template RestoreArrayAndMemtype<PETSC_MEMORY_ACCESS_READ_WRITE>);

1042:   VecSetOp_CUPM(getarraywriteandmemtype, nullptr, D::template GetArrayAndMemtype<PETSC_MEMORY_ACCESS_WRITE>);
1043:   VecSetOp_CUPM(restorearraywriteandmemtype, nullptr, [](Vec v, PetscScalar **a, PetscMemType *) { return D::template RestoreArrayAndMemtype<PETSC_MEMORY_ACCESS_WRITE>(v, a); });

1045:   VecSetOp_CUPM(getarrayreadandmemtype, nullptr, [](Vec v, const PetscScalar **a, PetscMemType *m) { return D::template GetArrayAndMemtype<PETSC_MEMORY_ACCESS_READ>(v, const_cast<PetscScalar **>(a), m); });
1046:   VecSetOp_CUPM(restorearrayreadandmemtype, nullptr, [](Vec v, const PetscScalar **a) { return D::template RestoreArrayAndMemtype<PETSC_MEMORY_ACCESS_READ>(v, const_cast<PetscScalar **>(a)); });
1047:   VecSetOp_CUPM(getarrayandmemtypeasync, nullptr, GetArrayAndMemtypeAsync);

1049:   // set the functions that are always sequential
1050:   using VecSeq_T = VecSeq_CUPM<T>;
1051:   VecSetOp_CUPM(scale, VecScale_Seq, VecSeq_T::Scale);
1052:   VecSetOp_CUPM(copy, VecCopy_Seq, VecSeq_T::Copy);
1053:   VecSetOp_CUPM(set, VecSet_Seq, VecSeq_T::Set);
1054:   VecSetOp_CUPM(swap, VecSwap_Seq, VecSeq_T::Swap);
1055:   VecSetOp_CUPM(axpy, VecAXPY_Seq, VecSeq_T::AXPY);
1056:   VecSetOp_CUPM(axpby, VecAXPBY_Seq, VecSeq_T::AXPBY);
1057:   VecSetOp_CUPM(maxpy, VecMAXPY_Seq, VecSeq_T::MAXPY);
1058:   VecSetOp_CUPM(aypx, VecAYPX_Seq, VecSeq_T::AYPX);
1059:   VecSetOp_CUPM(waxpy, VecWAXPY_Seq, VecSeq_T::WAXPY);
1060:   VecSetOp_CUPM(axpbypcz, VecAXPBYPCZ_Seq, VecSeq_T::AXPBYPCZ);
1061:   VecSetOp_CUPM(pointwisemult, VecPointwiseMult_Seq, VecSeq_T::PointwiseMult);
1062:   VecSetOp_CUPM(pointwisedivide, VecPointwiseDivide_Seq, VecSeq_T::PointwiseDivide);
1063:   VecSetOp_CUPM(pointwisemax, VecPointwiseMax_Seq, VecSeq_T::PointwiseMax);
1064:   VecSetOp_CUPM(pointwisemaxabs, VecPointwiseMaxAbs_Seq, VecSeq_T::PointwiseMaxAbs);
1065:   VecSetOp_CUPM(pointwisemin, VecPointwiseMin_Seq, VecSeq_T::PointwiseMin);
1066:   VecSetOp_CUPM(setrandom, VecSetRandom_Seq, VecSeq_T::SetRandom);
1067:   VecSetOp_CUPM(dot_local, VecDot_Seq, VecSeq_T::Dot);
1068:   VecSetOp_CUPM(tdot_local, VecTDot_Seq, VecSeq_T::TDot);
1069:   VecSetOp_CUPM(norm_local, VecNorm_Seq, VecSeq_T::Norm);
1070:   VecSetOp_CUPM(mdot_local, VecMDot_Seq, VecSeq_T::MDot);
1071:   VecSetOp_CUPM(reciprocal, VecReciprocal_Default, VecSeq_T::Reciprocal);
1072:   VecSetOp_CUPM(conjugate, VecConjugate_Seq, VecSeq_T::Conjugate);
1073:   VecSetOp_CUPM(abs, nullptr, VecSeq_T::Abs);
1074:   VecSetOp_CUPM(sqrt, nullptr, VecSeq_T::SqrtAbs);
1075:   VecSetOp_CUPM(exp, nullptr, VecSeq_T::Exp);
1076:   VecSetOp_CUPM(log, nullptr, VecSeq_T::Log);
1077:   VecSetOp_CUPM(shift, nullptr, VecSeq_T::Shift);
1078:   VecSetOp_CUPM(dotnorm2, nullptr, D::DotNorm2);
1079:   VecSetOp_CUPM(getlocalvector, nullptr, VecSeq_T::template GetLocalVector<PETSC_MEMORY_ACCESS_READ_WRITE>);
1080:   VecSetOp_CUPM(restorelocalvector, nullptr, VecSeq_T::template RestoreLocalVector<PETSC_MEMORY_ACCESS_READ_WRITE>);
1081:   VecSetOp_CUPM(getlocalvectorread, nullptr, VecSeq_T::template GetLocalVector<PETSC_MEMORY_ACCESS_READ>);
1082:   VecSetOp_CUPM(restorelocalvectorread, nullptr, VecSeq_T::template RestoreLocalVector<PETSC_MEMORY_ACCESS_READ>);
1083:   VecSetOp_CUPM(sum, nullptr, VecSeq_T::Sum);
1084:   VecSetOp_CUPM(errorwnorm, nullptr, D::ErrorWnorm);
1085:   VecSetOp_CUPM(duplicatevecs, VecDuplicateVecs_Default, VecDuplicateVecs_Default);
1086:   VecSetOp_CUPM(setstdbasis, nullptr, VecSeq_T::SetStdBasis);
1087:   // Finish pending transfers before CPU operations can access the host array.
1088:   if (usehost) PetscCall(PetscDeviceContextSynchronize(dctx));
1089:   PetscFunctionReturn(PETSC_SUCCESS);
1090: }

1092: // Called from VecGetSubVector()
1093: template <device::cupm::DeviceType T, typename D>
1094: inline PetscErrorCode Vec_CUPMBase<T, D>::GetArrays_CUPMBase(Vec v, const PetscScalar **host_array, const PetscScalar **device_array, PetscOffloadMask *mask, PetscDeviceContext dctx) noexcept
1095: {
1096:   PetscFunctionBegin;
1097:   PetscCheckTypeNames(v, VECSEQCUPM(), VECMPICUPM());
1098:   if (host_array) {
1099:     PetscCall(HostAllocateCheck_(dctx, v));
1100:     *host_array = VecIMPLCast(v)->array;
1101:   }
1102:   if (device_array) {
1103:     PetscCall(DeviceAllocateCheck_(dctx, v));
1104:     *device_array = VecCUPMCast(v)->array_d;
1105:   }
1106:   if (mask) *mask = v->offloadmask;
1107:   PetscFunctionReturn(PETSC_SUCCESS);
1108: }

1110: template <device::cupm::DeviceType T, typename D>
1111: inline PetscErrorCode Vec_CUPMBase<T, D>::ResetPreallocationCOO_CUPMBase(Vec v, PetscDeviceContext dctx) noexcept
1112: {
1113:   PetscFunctionBegin;
1114:   if (const auto vcu = VecCUPMCast(v)) {
1115:     cupmStream_t stream;
1116:     // clang-format off
1117:     const auto   cntptrs = util::make_array(
1118:       std::ref(vcu->jmap1_d),
1119:       std::ref(vcu->perm1_d),
1120:       std::ref(vcu->imap2_d),
1121:       std::ref(vcu->jmap2_d),
1122:       std::ref(vcu->perm2_d),
1123:       std::ref(vcu->Cperm_d)
1124:     );
1125:     // clang-format on

1127:     PetscCall(GetHandlesFrom_(dctx, &stream));
1128:     for (auto &&ptr : cntptrs) PetscCallCUPM(cupmFreeAsync(ptr.get(), stream));
1129:     for (auto &&ptr : util::make_array(std::ref(vcu->sendbuf_d), std::ref(vcu->recvbuf_d))) PetscCallCUPM(cupmFreeAsync(ptr.get(), stream));
1130:   }
1131:   PetscFunctionReturn(PETSC_SUCCESS);
1132: }

1134: template <device::cupm::DeviceType T, typename D>
1135: template <std::size_t NCount, std::size_t NScal>
1136: inline PetscErrorCode Vec_CUPMBase<T, D>::SetPreallocationCOO_CUPMBase(Vec v, PetscCount, const PetscInt[], PetscDeviceContext dctx, const std::array<CooPair<PetscCount>, NCount> &extra_cntptrs, const std::array<CooPair<PetscScalar>, NScal> &bufptrs) noexcept
1137: {
1138:   PetscFunctionBegin;
1139:   PetscCall(ResetPreallocationCOO_CUPMBase(v, dctx));
1140:   // need to instantiate the private pointer if not already
1141:   PetscCall(VecCUPMAllocateCheck_(v));
1142:   {
1143:     const auto vimpl = VecIMPLCast(v);
1144:     const auto vcu   = VecCUPMCast(v);
1145:     // clang-format off
1146:     const auto cntptrs = util::concat_array(
1147:       util::make_array(
1148:         make_coo_pair(vcu->jmap1_d, vimpl->jmap1, v->map->n + 1),
1149:         make_coo_pair(vcu->perm1_d, vimpl->perm1, vimpl->tot1)
1150:       ),
1151:       extra_cntptrs
1152:     );
1153:     // clang-format on
1154:     cupmStream_t stream;

1156:     PetscCall(GetHandlesFrom_(dctx, &stream));
1157:     // allocate
1158:     for (auto &elem : cntptrs) PetscCall(PetscCUPMMallocAsync(&elem.device, elem.size, stream));
1159:     for (auto &elem : bufptrs) PetscCall(PetscCUPMMallocAsync(&elem.device, elem.size, stream));
1160:     // copy
1161:     for (const auto &elem : cntptrs) PetscCall(PetscCUPMMemcpyAsync(elem.device, elem.host, elem.size, cupmMemcpyHostToDevice, stream, true));
1162:     for (const auto &elem : bufptrs) PetscCall(PetscCUPMMemcpyAsync(elem.device, elem.host, elem.size, cupmMemcpyHostToDevice, stream, true));
1163:   }
1164:   PetscFunctionReturn(PETSC_SUCCESS);
1165: }

1167: template <device::cupm::DeviceType T, typename D>
1168: inline PetscErrorCode Vec_CUPMBase<T, D>::Convert_IMPL_IMPLCUPM(Vec v) noexcept
1169: {
1170:   const auto         n        = v->map->n;
1171:   const auto         vimpl    = VecIMPLCast(v);
1172:   auto              &impl_arr = vimpl->array;
1173:   PetscBool          set      = PETSC_FALSE;
1174:   PetscDeviceContext dctx;

1176:   PetscFunctionBegin;
1177:   // If users do not explicitly require pinned memory, we prefer keeping the vector's regular
1178:   // host array
1179:   PetscCall(VecCUPMCheckMinimumPinnedMemory_Internal(v, &set));
1180:   if (set && impl_arr && ((n * sizeof(*impl_arr)) > v->minimum_bytes_pinned_memory)) {
1181:     auto        &impl_alloc = vimpl->array_allocated;
1182:     PetscScalar *new_arr;

1184:     // users require pinned memory
1185:     {
1186:       // Allocate pinned memory and copy over the old array
1187:       const auto useit = UseCUPMHostAlloc(PETSC_TRUE);

1189:       PetscCall(PetscMalloc1(n, &new_arr));
1190:       PetscCall(PetscArraycpy(new_arr, impl_arr, n));
1191:     }
1192:     PetscCall(PetscFree(impl_alloc));
1193:     impl_arr         = new_arr;
1194:     impl_alloc       = new_arr;
1195:     v->offloadmask   = PETSC_OFFLOAD_CPU;
1196:     v->pinned_memory = PETSC_TRUE;
1197:   }
1198:   PetscCall(GetHandles_(&dctx));
1199:   PetscCall(Initialize_CUPMBase(v, PETSC_FALSE, impl_arr, nullptr, dctx));
1200:   PetscFunctionReturn(PETSC_SUCCESS);
1201: }

1203:   #define PETSC_VEC_CUPM_BASE_CLASS_HEADER(name, Tp, ...) \
1204:     PETSC_CUPMOBJECT_HEADER(Tp); \
1205:     using name = ::Petsc::vec::cupm::impl::Vec_CUPMBase<Tp, __VA_ARGS__>; \
1206:     friend name; \
1207:     /* introspection */ \
1208:     using name::VecCUPMCast; \
1209:     using name::VecIMPLCast; \
1210:     using name::VECIMPLCUPM; \
1211:     using name::VECIMPL; \
1212:     using name::VECSEQCUPM; \
1213:     using name::VECMPICUPM; \
1214:     using name::VECCUPM; \
1215:     using name::VecView_Debug; \
1216:     /* utility */ \
1217:     using typename name::Vec_CUPM; \
1218:     using name::VecCUPMAllocateCheck_; \
1219:     using name::VecIMPLAllocateCheck_; \
1220:     using name::HostAllocateCheck_; \
1221:     using name::DeviceAllocateCheck_; \
1222:     using name::CopyToDevice_; \
1223:     using name::CopyToHost_; \
1224:     using name::Create; \
1225:     using name::Destroy; \
1226:     using name::GetArray; \
1227:     using name::RestoreArray; \
1228:     using name::GetArrayAndMemtype; \
1229:     using name::RestoreArrayAndMemtype; \
1230:     using name::PlaceArray; \
1231:     using name::ReplaceArray; \
1232:     using name::ResetArray; \
1233:     /* base functions */ \
1234:     using name::Create_CUPMBase; \
1235:     using name::Initialize_CUPMBase; \
1236:     using name::Duplicate_CUPMBase; \
1237:     using name::BindToCPU_CUPMBase; \
1238:     using name::Create_CUPM; \
1239:     using name::DeviceArrayRead; \
1240:     using name::DeviceArrayWrite; \
1241:     using name::DeviceArrayReadWrite; \
1242:     using name::HostArrayRead; \
1243:     using name::HostArrayWrite; \
1244:     using name::HostArrayReadWrite; \
1245:     using name::ResetPreallocationCOO_CUPMBase; \
1246:     using name::SetPreallocationCOO_CUPMBase; \
1247:     using name::Convert_IMPL_IMPLCUPM;

1249: } // namespace impl

1251: } // namespace cupm

1253: } // namespace vec

1255: } // namespace Petsc

1257: #endif // __cplusplus && PetscDefined(HAVE_DEVICE)