Actual source code: vecseqcupm_impl.hpp
1: #pragma once
3: #include "vecseqcupm.hpp"
5: #include <petsc/private/randomimpl.h>
7: #include "../src/sys/objects/device/impls/cupm/cupmthrustutility.hpp"
8: #include "../src/sys/objects/device/impls/cupm/kernels.hpp"
10: #if PetscDefined(USE_COMPLEX)
11: #include <thrust/transform_reduce.h>
12: #endif
13: #include <thrust/transform.h>
14: #include <thrust/reduce.h>
15: #include <thrust/functional.h>
16: #include <thrust/tuple.h>
17: #include <thrust/device_ptr.h>
18: #include <thrust/iterator/zip_iterator.h>
19: #include <thrust/iterator/counting_iterator.h>
20: #include <thrust/iterator/constant_iterator.h>
21: #include <thrust/inner_product.h>
23: namespace Petsc
24: {
26: namespace vec
27: {
29: namespace cupm
30: {
32: namespace impl
33: {
35: // ==========================================================================================
36: // VecSeq_CUPM - Private API
37: // ==========================================================================================
39: template <device::cupm::DeviceType T>
40: inline Vec_Seq *VecSeq_CUPM<T>::VecIMPLCast_(Vec v) noexcept
41: {
42: return static_cast<Vec_Seq *>(v->data);
43: }
45: template <device::cupm::DeviceType T>
46: inline constexpr VecType VecSeq_CUPM<T>::VECIMPLCUPM_() noexcept
47: {
48: return VECSEQCUPM();
49: }
51: template <device::cupm::DeviceType T>
52: inline constexpr VecType VecSeq_CUPM<T>::VECIMPL_() noexcept
53: {
54: return VECSEQ;
55: }
57: template <device::cupm::DeviceType T>
58: inline PetscErrorCode VecSeq_CUPM<T>::ClearAsyncFunctions(Vec v) noexcept
59: {
60: PetscFunctionBegin;
61: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(Abs), nullptr));
62: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(AXPBY), nullptr));
63: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(AXPBYPCZ), nullptr));
64: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(AXPY), nullptr));
65: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(AYPX), nullptr));
66: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(Conjugate), nullptr));
67: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(Copy), nullptr));
68: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(Exp), nullptr));
69: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(Log), nullptr));
70: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(MAXPY), nullptr));
71: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(PointwiseDivide), nullptr));
72: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(PointwiseMax), nullptr));
73: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(PointwiseMaxAbs), nullptr));
74: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(PointwiseMin), nullptr));
75: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(PointwiseMult), nullptr));
76: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(Reciprocal), nullptr));
77: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(Scale), nullptr));
78: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(Set), nullptr));
79: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(Shift), nullptr));
80: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(SqrtAbs), nullptr));
81: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(Swap), nullptr));
82: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(WAXPY), nullptr));
83: PetscFunctionReturn(PETSC_SUCCESS);
84: }
86: template <device::cupm::DeviceType T>
87: inline PetscErrorCode VecSeq_CUPM<T>::InitializeAsyncFunctions(Vec v) noexcept
88: {
89: PetscFunctionBegin;
90: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(Abs), VecSeq_CUPM<T>::AbsAsync));
91: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(AXPBY), VecSeq_CUPM<T>::AXPBYAsync));
92: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(AXPBYPCZ), VecSeq_CUPM<T>::AXPBYPCZAsync));
93: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(AXPY), VecSeq_CUPM<T>::AXPYAsync));
94: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(AYPX), VecSeq_CUPM<T>::AYPXAsync));
95: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(Conjugate), VecSeq_CUPM<T>::ConjugateAsync));
96: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(Copy), VecSeq_CUPM<T>::CopyAsync));
97: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(Exp), VecSeq_CUPM<T>::ExpAsync));
98: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(Log), VecSeq_CUPM<T>::LogAsync));
99: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(MAXPY), VecSeq_CUPM<T>::MAXPYAsync));
100: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(PointwiseDivide), VecSeq_CUPM<T>::PointwiseDivideAsync));
101: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(PointwiseMax), VecSeq_CUPM<T>::PointwiseMaxAsync));
102: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(PointwiseMaxAbs), VecSeq_CUPM<T>::PointwiseMaxAbsAsync));
103: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(PointwiseMin), VecSeq_CUPM<T>::PointwiseMinAsync));
104: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(PointwiseMult), VecSeq_CUPM<T>::PointwiseMultAsync));
105: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(Reciprocal), VecSeq_CUPM<T>::ReciprocalAsync));
106: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(Scale), VecSeq_CUPM<T>::ScaleAsync));
107: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(Set), VecSeq_CUPM<T>::SetAsync));
108: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(Shift), VecSeq_CUPM<T>::ShiftAsync));
109: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(SqrtAbs), VecSeq_CUPM<T>::SqrtAbsAsync));
110: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(Swap), VecSeq_CUPM<T>::SwapAsync));
111: PetscCall(PetscObjectComposeFunction(PetscObjectCast(v), VecAsyncFnName(WAXPY), VecSeq_CUPM<T>::WAXPYAsync));
112: PetscFunctionReturn(PETSC_SUCCESS);
113: }
115: template <device::cupm::DeviceType T>
116: inline PetscErrorCode VecSeq_CUPM<T>::VecDestroy_IMPL_(Vec v) noexcept
117: {
118: PetscFunctionBegin;
119: PetscCall(ClearAsyncFunctions(v));
120: PetscCall(VecDestroy_Seq(v));
121: PetscFunctionReturn(PETSC_SUCCESS);
122: }
124: template <device::cupm::DeviceType T>
125: inline PetscErrorCode VecSeq_CUPM<T>::VecResetArray_IMPL_(Vec v) noexcept
126: {
127: return VecResetArray_Seq(v);
128: }
130: template <device::cupm::DeviceType T>
131: inline PetscErrorCode VecSeq_CUPM<T>::VecPlaceArray_IMPL_(Vec v, const PetscScalar *a) noexcept
132: {
133: return VecPlaceArray_Seq(v, a);
134: }
136: template <device::cupm::DeviceType T>
137: inline PetscErrorCode VecSeq_CUPM<T>::VecCreate_IMPL_Private_(Vec v, PetscBool *alloc_missing, PetscInt, PetscScalar *host_array) noexcept
138: {
139: PetscMPIInt size;
141: PetscFunctionBegin;
142: if (alloc_missing) *alloc_missing = PETSC_FALSE;
143: PetscCallMPI(MPI_Comm_size(PetscObjectComm(PetscObjectCast(v)), &size));
144: PetscCheck(size <= 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Must create VecSeq on communicator of size 1, have size %d", size);
145: PetscCall(VecCreate_Seq_Private(v, host_array));
146: PetscCall(InitializeAsyncFunctions(v));
147: PetscFunctionReturn(PETSC_SUCCESS);
148: }
150: // for functions with an early return based one vec size we still need to artificially bump the
151: // object state. This is to prevent the following:
152: //
153: // 0. Suppose you have a Vec {
154: // rank 0: [0],
155: // rank 1: [<empty>]
156: // }
157: // 1. both ranks have Vec with PetscObjectState = 0, stashed norm of 0
158: // 2. Vec enters e.g. VecSet(10)
159: // 3. rank 1 has local size 0 and bails immediately
160: // 4. rank 0 has local size 1 and enters function, eventually calls DeviceArrayWrite()
161: // 5. DeviceArrayWrite() calls PetscObjectStateIncrease(), now state = 1
162: // 6. Vec enters VecNorm(), and calls VecNormAvailable()
163: // 7. rank 1 has object state = 0, equal to stash and returns early with norm = 0
164: // 8. rank 0 has object state = 1, not equal to stash, continues to impl function
165: // 9. rank 0 deadlocks on MPI_Allreduce() because rank 1 bailed early
166: template <device::cupm::DeviceType T>
167: inline PetscErrorCode VecSeq_CUPM<T>::MaybeIncrementEmptyLocalVec(Vec v) noexcept
168: {
169: PetscFunctionBegin;
170: if (PetscUnlikely((v->map->n == 0) && (v->map->N != 0))) PetscCall(PetscObjectStateIncrease(PetscObjectCast(v)));
171: PetscFunctionReturn(PETSC_SUCCESS);
172: }
174: template <device::cupm::DeviceType T>
175: inline PetscErrorCode VecSeq_CUPM<T>::CreateSeqCUPM_(Vec v, PetscDeviceContext dctx, PetscScalar *host_array, PetscScalar *device_array) noexcept
176: {
177: PetscFunctionBegin;
178: PetscCall(base_type::VecCreate_IMPL_Private(v, nullptr, 0, host_array));
179: PetscCall(Initialize_CUPMBase(v, PETSC_FALSE, host_array, device_array, dctx));
180: PetscFunctionReturn(PETSC_SUCCESS);
181: }
183: template <device::cupm::DeviceType T>
184: template <typename BinaryFuncT>
185: inline PetscErrorCode VecSeq_CUPM<T>::PointwiseBinary_(BinaryFuncT &&binary, Vec xin, Vec yin, Vec zout, PetscDeviceContext dctx) noexcept
186: {
187: PetscFunctionBegin;
188: if (const auto n = zout->map->n) {
189: cupmStream_t stream;
191: PetscCall(PetscDeviceContextGetOptionalNullContext_Internal(&dctx));
192: PetscCall(GetHandlesFrom_(dctx, &stream));
193: // clang-format off
194: PetscCallThrust(
195: const auto dxptr = thrust::device_pointer_cast(DeviceArrayRead(dctx, xin).data());
197: THRUST_CALL(
198: thrust::transform,
199: stream,
200: dxptr, dxptr + n,
201: thrust::device_pointer_cast(DeviceArrayRead(dctx, yin).data()),
202: thrust::device_pointer_cast(DeviceArrayWrite(dctx, zout).data()),
203: std::forward<BinaryFuncT>(binary)
204: )
205: );
206: // clang-format on
207: PetscCall(PetscLogGpuFlops(n));
208: PetscCall(PetscDeviceContextSynchronizeIfGlobalBlocking_Internal(dctx));
209: } else {
210: PetscCall(MaybeIncrementEmptyLocalVec(zout));
211: }
212: PetscFunctionReturn(PETSC_SUCCESS);
213: }
215: template <device::cupm::DeviceType T>
216: template <typename BinaryFuncT>
217: inline PetscErrorCode VecSeq_CUPM<T>::PointwiseBinaryDispatch_(PetscErrorCode (*VecSeqFunction)(Vec, Vec, Vec), BinaryFuncT &&binary, Vec wout, Vec xin, Vec yin, PetscDeviceContext dctx) noexcept
218: {
219: PetscFunctionBegin;
220: if (xin->boundtocpu || yin->boundtocpu) {
221: PetscCall((*VecSeqFunction)(wout, xin, yin));
222: } else {
223: // note order of arguments! xin and yin are read, wout is written!
224: PetscCall(PointwiseBinary_(std::forward<BinaryFuncT>(binary), xin, yin, wout, dctx));
225: }
226: PetscFunctionReturn(PETSC_SUCCESS);
227: }
229: template <device::cupm::DeviceType T>
230: template <typename UnaryFuncT>
231: inline PetscErrorCode VecSeq_CUPM<T>::PointwiseUnary_(UnaryFuncT &&unary, Vec xinout, Vec yin, PetscDeviceContext dctx) noexcept
232: {
233: const auto inplace = !yin || (xinout == yin);
235: PetscFunctionBegin;
236: if (const auto n = xinout->map->n) {
237: cupmStream_t stream;
238: const auto apply = [&](PetscScalar *xinout, PetscScalar *yin = nullptr) {
239: PetscFunctionBegin;
240: // clang-format off
241: PetscCallThrust(
242: const auto xptr = thrust::device_pointer_cast(xinout);
244: THRUST_CALL(
245: thrust::transform,
246: stream,
247: xptr, xptr + n,
248: (yin && (yin != xinout)) ? thrust::device_pointer_cast(yin) : xptr,
249: std::forward<UnaryFuncT>(unary)
250: )
251: );
252: // clang-format on
253: PetscFunctionReturn(PETSC_SUCCESS);
254: };
256: PetscCall(PetscDeviceContextGetOptionalNullContext_Internal(&dctx));
257: PetscCall(GetHandlesFrom_(dctx, &stream));
258: if (inplace) {
259: PetscCall(apply(DeviceArrayReadWrite(dctx, xinout).data()));
260: } else {
261: PetscCall(apply(DeviceArrayRead(dctx, xinout).data(), DeviceArrayWrite(dctx, yin).data()));
262: }
263: PetscCall(PetscLogGpuFlops(n));
264: PetscCall(PetscDeviceContextSynchronizeIfGlobalBlocking_Internal(dctx));
265: } else {
266: if (inplace) {
267: PetscCall(MaybeIncrementEmptyLocalVec(xinout));
268: } else {
269: PetscCall(MaybeIncrementEmptyLocalVec(yin));
270: }
271: }
272: PetscFunctionReturn(PETSC_SUCCESS);
273: }
275: // ==========================================================================================
276: // VecSeq_CUPM - Public API - Constructors
277: // ==========================================================================================
279: // VecCreateSeqCUPM()
280: template <device::cupm::DeviceType T>
281: inline PetscErrorCode VecSeq_CUPM<T>::CreateSeqCUPM(MPI_Comm comm, PetscInt bs, PetscInt n, Vec *v, PetscBool call_set_type) noexcept
282: {
283: PetscFunctionBegin;
284: PetscCall(Create_CUPMBase(comm, bs, n, n, v, call_set_type));
285: PetscFunctionReturn(PETSC_SUCCESS);
286: }
288: // VecCreateSeqCUPMWithArrays()
289: template <device::cupm::DeviceType T>
290: inline PetscErrorCode VecSeq_CUPM<T>::CreateSeqCUPMWithBothArrays(MPI_Comm comm, PetscInt bs, PetscInt n, const PetscScalar host_array[], const PetscScalar device_array[], Vec *v) noexcept
291: {
292: PetscDeviceContext dctx;
294: PetscFunctionBegin;
295: PetscCall(GetHandles_(&dctx));
296: // do NOT call VecSetType(), otherwise ops->create() -> create() ->
297: // CreateSeqCUPM_() is called!
298: PetscCall(CreateSeqCUPM(comm, bs, n, v, PETSC_FALSE));
299: PetscCall(CreateSeqCUPM_(*v, dctx, PetscRemoveConstCast(host_array), PetscRemoveConstCast(device_array)));
300: PetscFunctionReturn(PETSC_SUCCESS);
301: }
303: // v->ops->duplicate
304: template <device::cupm::DeviceType T>
305: inline PetscErrorCode VecSeq_CUPM<T>::Duplicate(Vec v, Vec *y) noexcept
306: {
307: PetscDeviceContext dctx;
309: PetscFunctionBegin;
310: PetscCall(GetHandles_(&dctx));
311: PetscCall(Duplicate_CUPMBase(v, y, dctx));
312: PetscFunctionReturn(PETSC_SUCCESS);
313: }
315: // ==========================================================================================
316: // VecSeq_CUPM - Public API - Utility
317: // ==========================================================================================
319: // v->ops->bindtocpu
320: template <device::cupm::DeviceType T>
321: inline PetscErrorCode VecSeq_CUPM<T>::BindToCPU(Vec v, PetscBool usehost) noexcept
322: {
323: PetscDeviceContext dctx;
325: PetscFunctionBegin;
326: PetscCall(GetHandles_(&dctx));
327: PetscCall(BindToCPU_CUPMBase(v, usehost, dctx));
329: // REVIEW ME: this absolutely should be some sort of bulk mempcy rather than this mess
330: VecSetOp_CUPM(dot, VecDot_Seq, Dot);
331: VecSetOp_CUPM(norm, VecNorm_Seq, Norm);
332: VecSetOp_CUPM(tdot, VecTDot_Seq, TDot);
333: VecSetOp_CUPM(mdot, VecMDot_Seq, MDot);
334: VecSetOp_CUPM(resetarray, VecResetArray_Seq, base_type::template ResetArray<PETSC_MEMTYPE_HOST>);
335: VecSetOp_CUPM(placearray, VecPlaceArray_Seq, base_type::template PlaceArray<PETSC_MEMTYPE_HOST>);
336: v->ops->mtdot = v->ops->mtdot_local = VecMTDot_Seq;
337: VecSetOp_CUPM(max, VecMax_Seq, Max);
338: VecSetOp_CUPM(min, VecMin_Seq, Min);
339: VecSetOp_CUPM(setpreallocationcoo, VecSetPreallocationCOO_Seq, SetPreallocationCOO);
340: VecSetOp_CUPM(setvaluescoo, VecSetValuesCOO_Seq, SetValuesCOO);
341: PetscFunctionReturn(PETSC_SUCCESS);
342: }
344: // ==========================================================================================
345: // VecSeq_CUPM - Public API - Mutators
346: // ==========================================================================================
348: // v->ops->getlocalvector or v->ops->getlocalvectorread
349: template <device::cupm::DeviceType T>
350: template <PetscMemoryAccessMode access>
351: inline PetscErrorCode VecSeq_CUPM<T>::GetLocalVector(Vec v, Vec w) noexcept
352: {
353: PetscBool wisseqcupm;
355: PetscFunctionBegin;
356: PetscCheckTypeNames(v, VECSEQCUPM(), VECMPICUPM());
357: PetscCall(PetscObjectTypeCompare(PetscObjectCast(w), VECSEQCUPM(), &wisseqcupm));
358: if (wisseqcupm) {
359: if (const auto wseq = VecIMPLCast(w)) {
360: if (auto &alloced = wseq->array_allocated) {
361: const auto useit = UseCUPMHostAlloc(util::exchange(w->pinned_memory, PETSC_FALSE));
363: PetscCall(PetscFree(alloced));
364: }
365: wseq->array = nullptr;
366: wseq->unplacedarray = nullptr;
367: }
368: if (const auto wcu = VecCUPMCast(w)) {
369: if (auto &device_array = wcu->array_d) {
370: cupmStream_t stream;
372: PetscCall(GetHandles_(&stream));
373: PetscCallCUPM(cupmFreeAsync(device_array, stream));
374: }
375: PetscCall(PetscFree(w->spptr /* wcu */));
376: }
377: }
378: if (v->petscnative && wisseqcupm) {
379: PetscCall(PetscFree(w->data));
380: w->data = v->data;
381: w->offloadmask = v->offloadmask;
382: w->pinned_memory = v->pinned_memory;
383: w->spptr = v->spptr;
384: PetscCall(PetscObjectStateIncrease(PetscObjectCast(w)));
385: } else {
386: const auto array = &VecIMPLCast(w)->array;
388: if (access == PETSC_MEMORY_ACCESS_READ) {
389: PetscCall(VecGetArrayRead(v, const_cast<const PetscScalar **>(array)));
390: } else {
391: PetscCall(VecGetArray(v, array));
392: }
393: w->offloadmask = PETSC_OFFLOAD_CPU;
394: if (wisseqcupm) {
395: PetscDeviceContext dctx;
397: PetscCall(GetHandles_(&dctx));
398: PetscCall(DeviceAllocateCheck_(dctx, w));
399: }
400: }
401: PetscFunctionReturn(PETSC_SUCCESS);
402: }
404: // v->ops->restorelocalvector or v->ops->restorelocalvectorread
405: template <device::cupm::DeviceType T>
406: template <PetscMemoryAccessMode access>
407: inline PetscErrorCode VecSeq_CUPM<T>::RestoreLocalVector(Vec v, Vec w) noexcept
408: {
409: PetscBool wisseqcupm;
411: PetscFunctionBegin;
412: PetscCheckTypeNames(v, VECSEQCUPM(), VECMPICUPM());
413: PetscCall(PetscObjectTypeCompare(PetscObjectCast(w), VECSEQCUPM(), &wisseqcupm));
414: if (v->petscnative && wisseqcupm) {
415: // the assignments to nullptr are __critical__, as w may persist after this call returns
416: // and shouldn't share data with v!
417: v->pinned_memory = w->pinned_memory;
418: v->offloadmask = util::exchange(w->offloadmask, PETSC_OFFLOAD_UNALLOCATED);
419: v->data = util::exchange(w->data, nullptr);
420: v->spptr = util::exchange(w->spptr, nullptr);
421: } else {
422: const auto array = &VecIMPLCast(w)->array;
424: if (access == PETSC_MEMORY_ACCESS_READ) {
425: PetscCall(VecRestoreArrayRead(v, const_cast<const PetscScalar **>(array)));
426: } else {
427: PetscCall(VecRestoreArray(v, array));
428: }
429: if (w->spptr && wisseqcupm) {
430: cupmStream_t stream;
432: PetscCall(GetHandles_(&stream));
433: PetscCallCUPM(cupmFreeAsync(VecCUPMCast(w)->array_d, stream));
434: PetscCall(PetscFree(w->spptr));
435: }
436: }
437: PetscFunctionReturn(PETSC_SUCCESS);
438: }
440: // ==========================================================================================
441: // VecSeq_CUPM - Public API - Compute Methods
442: // ==========================================================================================
444: // VecAYPXAsync_Private
445: template <device::cupm::DeviceType T>
446: inline PetscErrorCode VecSeq_CUPM<T>::AYPXAsync(Vec yin, PetscScalar alpha, Vec xin, PetscDeviceContext dctx) noexcept
447: {
448: const auto n = static_cast<cupmBlasInt_t>(yin->map->n);
449: PetscBool xiscupm;
451: PetscFunctionBegin;
452: PetscCall(PetscObjectTypeCompareAny(PetscObjectCast(xin), &xiscupm, VECSEQCUPM(), VECMPICUPM(), ""));
453: if (!xiscupm) {
454: PetscCall(VecAYPX_Seq(yin, alpha, xin));
455: PetscFunctionReturn(PETSC_SUCCESS);
456: }
457: PetscCall(PetscDeviceContextGetOptionalNullContext_Internal(&dctx));
458: if (alpha == PetscScalar(0.0)) {
459: cupmStream_t stream;
461: PetscCall(GetHandlesFrom_(dctx, &stream));
462: PetscCall(PetscLogGpuTimeBegin());
463: PetscCall(PetscCUPMMemcpyAsync(DeviceArrayWrite(dctx, yin).data(), DeviceArrayRead(dctx, xin).data(), n, cupmMemcpyDeviceToDevice, stream));
464: PetscCall(PetscLogGpuTimeEnd());
465: } else if (n) {
466: const auto alphaIsOne = alpha == PetscScalar(1.0);
467: const auto calpha = cupmScalarPtrCast(&alpha);
468: cupmBlasHandle_t cupmBlasHandle;
470: PetscCall(GetHandlesFrom_(dctx, &cupmBlasHandle));
471: {
472: const auto yptr = DeviceArrayReadWrite(dctx, yin);
473: const auto xptr = DeviceArrayRead(dctx, xin);
475: PetscCall(PetscLogGpuTimeBegin());
476: if (alphaIsOne) {
477: PetscCallCUPMBLAS(cupmBlasXaxpy(cupmBlasHandle, n, calpha, xptr.cupmdata(), 1, yptr.cupmdata(), 1));
478: } else {
479: const auto one = cupmScalarCast(1.0);
481: PetscCallCUPMBLAS(cupmBlasXscal(cupmBlasHandle, n, calpha, yptr.cupmdata(), 1));
482: PetscCallCUPMBLAS(cupmBlasXaxpy(cupmBlasHandle, n, &one, xptr.cupmdata(), 1, yptr.cupmdata(), 1));
483: }
484: PetscCall(PetscLogGpuTimeEnd());
485: }
486: PetscCall(PetscLogGpuFlops((alphaIsOne ? 1 : 2) * n));
487: }
488: if (n > 0) PetscCall(PetscDeviceContextSynchronizeIfGlobalBlocking_Internal(dctx));
489: PetscFunctionReturn(PETSC_SUCCESS);
490: }
492: // v->ops->aypx
493: template <device::cupm::DeviceType T>
494: inline PetscErrorCode VecSeq_CUPM<T>::AYPX(Vec yin, PetscScalar alpha, Vec xin) noexcept
495: {
496: PetscFunctionBegin;
497: PetscCall(AYPXAsync(yin, alpha, xin, nullptr));
498: PetscFunctionReturn(PETSC_SUCCESS);
499: }
501: // VecAXPYAsync_Private
502: template <device::cupm::DeviceType T>
503: inline PetscErrorCode VecSeq_CUPM<T>::AXPYAsync(Vec yin, PetscScalar alpha, Vec xin, PetscDeviceContext dctx) noexcept
504: {
505: PetscBool xiscupm;
507: PetscFunctionBegin;
508: PetscCall(PetscObjectTypeCompareAny(PetscObjectCast(xin), &xiscupm, VECSEQCUPM(), VECMPICUPM(), ""));
509: if (xiscupm) {
510: const auto n = static_cast<cupmBlasInt_t>(yin->map->n);
511: cupmBlasHandle_t cupmBlasHandle;
513: PetscCall(PetscDeviceContextGetOptionalNullContext_Internal(&dctx));
514: PetscCall(GetHandlesFrom_(dctx, &cupmBlasHandle));
515: PetscCall(PetscLogGpuTimeBegin());
516: PetscCallCUPMBLAS(cupmBlasXaxpy(cupmBlasHandle, n, cupmScalarPtrCast(&alpha), DeviceArrayRead(dctx, xin), 1, DeviceArrayReadWrite(dctx, yin), 1));
517: PetscCall(PetscLogGpuTimeEnd());
518: PetscCall(PetscLogGpuFlops(2 * n));
519: if (n > 0) PetscCall(PetscDeviceContextSynchronizeIfGlobalBlocking_Internal(dctx));
520: } else {
521: PetscCall(VecAXPY_Seq(yin, alpha, xin));
522: }
523: PetscFunctionReturn(PETSC_SUCCESS);
524: }
526: // v->ops->axpy
527: template <device::cupm::DeviceType T>
528: inline PetscErrorCode VecSeq_CUPM<T>::AXPY(Vec yin, PetscScalar alpha, Vec xin) noexcept
529: {
530: PetscFunctionBegin;
531: PetscCall(AXPYAsync(yin, alpha, xin, nullptr));
532: PetscFunctionReturn(PETSC_SUCCESS);
533: }
535: namespace detail
536: {
538: struct divides {
539: PETSC_HOSTDEVICE_INLINE_DECL PetscScalar operator()(const PetscScalar &lhs, const PetscScalar &rhs) const noexcept { return rhs == PetscScalar{0.0} ? rhs : lhs / rhs; }
540: };
542: } // namespace detail
544: // VecPointwiseDivideAsync_Private
545: template <device::cupm::DeviceType T>
546: inline PetscErrorCode VecSeq_CUPM<T>::PointwiseDivideAsync(Vec wout, Vec xin, Vec yin, PetscDeviceContext dctx) noexcept
547: {
548: PetscFunctionBegin;
549: PetscCall(PointwiseBinaryDispatch_(VecPointwiseDivide_Seq, detail::divides{}, wout, xin, yin, dctx));
550: PetscFunctionReturn(PETSC_SUCCESS);
551: }
553: // v->ops->pointwisedivide
554: template <device::cupm::DeviceType T>
555: inline PetscErrorCode VecSeq_CUPM<T>::PointwiseDivide(Vec wout, Vec xin, Vec yin) noexcept
556: {
557: PetscFunctionBegin;
558: PetscCall(PointwiseDivideAsync(wout, xin, yin, nullptr));
559: PetscFunctionReturn(PETSC_SUCCESS);
560: }
562: // VecPointwiseMultAsync_Private
563: template <device::cupm::DeviceType T>
564: inline PetscErrorCode VecSeq_CUPM<T>::PointwiseMultAsync(Vec wout, Vec xin, Vec yin, PetscDeviceContext dctx) noexcept
565: {
566: PetscFunctionBegin;
567: PetscCall(PointwiseBinaryDispatch_(VecPointwiseMult_Seq, thrust::multiplies<PetscScalar>{}, wout, xin, yin, dctx));
568: PetscFunctionReturn(PETSC_SUCCESS);
569: }
571: // v->ops->pointwisemult
572: template <device::cupm::DeviceType T>
573: inline PetscErrorCode VecSeq_CUPM<T>::PointwiseMult(Vec wout, Vec xin, Vec yin) noexcept
574: {
575: PetscFunctionBegin;
576: PetscCall(PointwiseMultAsync(wout, xin, yin, nullptr));
577: PetscFunctionReturn(PETSC_SUCCESS);
578: }
580: namespace detail
581: {
583: struct MaximumRealPart {
584: PETSC_HOSTDEVICE_INLINE_DECL PetscScalar operator()(const PetscScalar &lhs, const PetscScalar &rhs) const noexcept { return thrust::maximum<PetscReal>{}(PetscRealPart(lhs), PetscRealPart(rhs)); }
585: };
587: } // namespace detail
589: // VecPointwiseMaxAsync_Private
590: template <device::cupm::DeviceType T>
591: inline PetscErrorCode VecSeq_CUPM<T>::PointwiseMaxAsync(Vec wout, Vec xin, Vec yin, PetscDeviceContext dctx) noexcept
592: {
593: PetscFunctionBegin;
594: PetscCall(PointwiseBinaryDispatch_(VecPointwiseMax_Seq, detail::MaximumRealPart{}, wout, xin, yin, dctx));
595: PetscFunctionReturn(PETSC_SUCCESS);
596: }
598: // v->ops->pointwisemax
599: template <device::cupm::DeviceType T>
600: inline PetscErrorCode VecSeq_CUPM<T>::PointwiseMax(Vec wout, Vec xin, Vec yin) noexcept
601: {
602: PetscFunctionBegin;
603: PetscCall(PointwiseMaxAsync(wout, xin, yin, nullptr));
604: PetscFunctionReturn(PETSC_SUCCESS);
605: }
607: namespace detail
608: {
610: struct MaximumAbsoluteValue {
611: PETSC_HOSTDEVICE_INLINE_DECL PetscScalar operator()(const PetscScalar &lhs, const PetscScalar &rhs) const noexcept { return thrust::maximum<PetscReal>{}(PetscAbsScalar(lhs), PetscAbsScalar(rhs)); }
612: };
614: } // namespace detail
616: // VecPointwiseMaxAbsAsync_Private
617: template <device::cupm::DeviceType T>
618: inline PetscErrorCode VecSeq_CUPM<T>::PointwiseMaxAbsAsync(Vec wout, Vec xin, Vec yin, PetscDeviceContext dctx) noexcept
619: {
620: PetscFunctionBegin;
621: PetscCall(PointwiseBinaryDispatch_(VecPointwiseMaxAbs_Seq, detail::MaximumAbsoluteValue{}, wout, xin, yin, dctx));
622: PetscFunctionReturn(PETSC_SUCCESS);
623: }
625: // v->ops->pointwisemaxabs
626: template <device::cupm::DeviceType T>
627: inline PetscErrorCode VecSeq_CUPM<T>::PointwiseMaxAbs(Vec wout, Vec xin, Vec yin) noexcept
628: {
629: PetscFunctionBegin;
630: PetscCall(PointwiseMaxAbsAsync(wout, xin, yin, nullptr));
631: PetscFunctionReturn(PETSC_SUCCESS);
632: }
634: namespace detail
635: {
637: struct MinimumRealPart {
638: PETSC_HOSTDEVICE_INLINE_DECL PetscScalar operator()(const PetscScalar &lhs, const PetscScalar &rhs) const noexcept { return thrust::minimum<PetscReal>{}(PetscRealPart(lhs), PetscRealPart(rhs)); }
639: };
641: } // namespace detail
643: // VecPointwiseMinAsync_Private
644: template <device::cupm::DeviceType T>
645: inline PetscErrorCode VecSeq_CUPM<T>::PointwiseMinAsync(Vec wout, Vec xin, Vec yin, PetscDeviceContext dctx) noexcept
646: {
647: PetscFunctionBegin;
648: PetscCall(PointwiseBinaryDispatch_(VecPointwiseMin_Seq, detail::MinimumRealPart{}, wout, xin, yin, dctx));
649: PetscFunctionReturn(PETSC_SUCCESS);
650: }
652: // v->ops->pointwisemin
653: template <device::cupm::DeviceType T>
654: inline PetscErrorCode VecSeq_CUPM<T>::PointwiseMin(Vec wout, Vec xin, Vec yin) noexcept
655: {
656: PetscFunctionBegin;
657: PetscCall(PointwiseMinAsync(wout, xin, yin, nullptr));
658: PetscFunctionReturn(PETSC_SUCCESS);
659: }
661: namespace detail
662: {
664: struct Reciprocal {
665: PETSC_HOSTDEVICE_INLINE_DECL PetscScalar operator()(const PetscScalar &s) const noexcept
666: {
667: // yes all of this verbosity is needed because sometimes PetscScalar is a thrust::complex
668: // and then it matters whether we do s ? true : false vs s == 0, as well as whether we wrap
669: // everything in PetscScalar...
670: return s == PetscScalar{0.0} ? s : PetscScalar{1.0} / s;
671: }
672: };
674: } // namespace detail
676: // VecReciprocalAsync_Private
677: template <device::cupm::DeviceType T>
678: inline PetscErrorCode VecSeq_CUPM<T>::ReciprocalAsync(Vec xin, PetscDeviceContext dctx) noexcept
679: {
680: PetscFunctionBegin;
681: PetscCall(PointwiseUnary_(detail::Reciprocal{}, xin, nullptr, dctx));
682: PetscFunctionReturn(PETSC_SUCCESS);
683: }
685: // v->ops->reciprocal
686: template <device::cupm::DeviceType T>
687: inline PetscErrorCode VecSeq_CUPM<T>::Reciprocal(Vec xin) noexcept
688: {
689: PetscFunctionBegin;
690: PetscCall(ReciprocalAsync(xin, nullptr));
691: PetscFunctionReturn(PETSC_SUCCESS);
692: }
694: namespace detail
695: {
697: struct AbsoluteValue {
698: PETSC_HOSTDEVICE_INLINE_DECL PetscScalar operator()(const PetscScalar &s) const noexcept { return PetscAbsScalar(s); }
699: };
701: } // namespace detail
703: // VecAbsAsync_Private
704: template <device::cupm::DeviceType T>
705: inline PetscErrorCode VecSeq_CUPM<T>::AbsAsync(Vec xin, PetscDeviceContext dctx) noexcept
706: {
707: PetscFunctionBegin;
708: PetscCall(PointwiseUnary_(detail::AbsoluteValue{}, xin, nullptr, dctx));
709: PetscFunctionReturn(PETSC_SUCCESS);
710: }
712: // v->ops->abs
713: template <device::cupm::DeviceType T>
714: inline PetscErrorCode VecSeq_CUPM<T>::Abs(Vec xin) noexcept
715: {
716: PetscFunctionBegin;
717: PetscCall(AbsAsync(xin, nullptr));
718: PetscFunctionReturn(PETSC_SUCCESS);
719: }
721: namespace detail
722: {
724: struct SquareRootAbsoluteValue {
725: PETSC_HOSTDEVICE_INLINE_DECL PetscScalar operator()(const PetscScalar &s) const noexcept { return PetscSqrtReal(PetscAbsScalar(s)); }
726: };
728: } // namespace detail
730: // VecSqrtAbsAsync_Private
731: template <device::cupm::DeviceType T>
732: inline PetscErrorCode VecSeq_CUPM<T>::SqrtAbsAsync(Vec xin, PetscDeviceContext dctx) noexcept
733: {
734: PetscFunctionBegin;
735: PetscCall(PointwiseUnary_(detail::SquareRootAbsoluteValue{}, xin, nullptr, dctx));
736: PetscFunctionReturn(PETSC_SUCCESS);
737: }
739: // v->ops->sqrt
740: template <device::cupm::DeviceType T>
741: inline PetscErrorCode VecSeq_CUPM<T>::SqrtAbs(Vec xin) noexcept
742: {
743: PetscFunctionBegin;
744: PetscCall(SqrtAbsAsync(xin, nullptr));
745: PetscFunctionReturn(PETSC_SUCCESS);
746: }
748: namespace detail
749: {
751: struct Exponent {
752: PETSC_HOSTDEVICE_INLINE_DECL PetscScalar operator()(const PetscScalar &s) const noexcept { return PetscExpScalar(s); }
753: };
755: } // namespace detail
757: // VecExpAsync_Private
758: template <device::cupm::DeviceType T>
759: inline PetscErrorCode VecSeq_CUPM<T>::ExpAsync(Vec xin, PetscDeviceContext dctx) noexcept
760: {
761: PetscFunctionBegin;
762: PetscCall(PointwiseUnary_(detail::Exponent{}, xin, nullptr, dctx));
763: PetscFunctionReturn(PETSC_SUCCESS);
764: }
766: // v->ops->exp
767: template <device::cupm::DeviceType T>
768: inline PetscErrorCode VecSeq_CUPM<T>::Exp(Vec xin) noexcept
769: {
770: PetscFunctionBegin;
771: PetscCall(ExpAsync(xin, nullptr));
772: PetscFunctionReturn(PETSC_SUCCESS);
773: }
775: namespace detail
776: {
778: struct Logarithm {
779: PETSC_HOSTDEVICE_INLINE_DECL PetscScalar operator()(const PetscScalar &s) const noexcept { return PetscLogScalar(s); }
780: };
782: } // namespace detail
784: // VecLogAsync_Private
785: template <device::cupm::DeviceType T>
786: inline PetscErrorCode VecSeq_CUPM<T>::LogAsync(Vec xin, PetscDeviceContext dctx) noexcept
787: {
788: PetscFunctionBegin;
789: PetscCall(PointwiseUnary_(detail::Logarithm{}, xin, nullptr, dctx));
790: PetscFunctionReturn(PETSC_SUCCESS);
791: }
793: // v->ops->log
794: template <device::cupm::DeviceType T>
795: inline PetscErrorCode VecSeq_CUPM<T>::Log(Vec xin) noexcept
796: {
797: PetscFunctionBegin;
798: PetscCall(LogAsync(xin, nullptr));
799: PetscFunctionReturn(PETSC_SUCCESS);
800: }
802: // v->ops->waxpy
803: template <device::cupm::DeviceType T>
804: inline PetscErrorCode VecSeq_CUPM<T>::WAXPYAsync(Vec win, PetscScalar alpha, Vec xin, Vec yin, PetscDeviceContext dctx) noexcept
805: {
806: PetscFunctionBegin;
807: PetscCall(PetscDeviceContextGetOptionalNullContext_Internal(&dctx));
808: if (alpha == PetscScalar(0.0)) {
809: PetscCall(CopyAsync(yin, win, dctx));
810: } else if (const auto n = static_cast<cupmBlasInt_t>(win->map->n)) {
811: cupmBlasHandle_t cupmBlasHandle;
812: cupmStream_t stream;
814: PetscCall(GetHandlesFrom_(dctx, &cupmBlasHandle, NULL, &stream));
815: {
816: const auto wptr = DeviceArrayWrite(dctx, win);
818: PetscCall(PetscLogGpuTimeBegin());
819: PetscCall(PetscCUPMMemcpyAsync(wptr.data(), DeviceArrayRead(dctx, yin).data(), n, cupmMemcpyDeviceToDevice, stream, true));
820: PetscCallCUPMBLAS(cupmBlasXaxpy(cupmBlasHandle, n, cupmScalarPtrCast(&alpha), DeviceArrayRead(dctx, xin), 1, wptr.cupmdata(), 1));
821: PetscCall(PetscLogGpuTimeEnd());
822: }
823: PetscCall(PetscLogGpuFlops(2 * n));
824: PetscCall(PetscDeviceContextSynchronizeIfGlobalBlocking_Internal(dctx));
825: }
826: PetscFunctionReturn(PETSC_SUCCESS);
827: }
829: // v->ops->waxpy
830: template <device::cupm::DeviceType T>
831: inline PetscErrorCode VecSeq_CUPM<T>::WAXPY(Vec win, PetscScalar alpha, Vec xin, Vec yin) noexcept
832: {
833: PetscFunctionBegin;
834: PetscCall(WAXPYAsync(win, alpha, xin, yin, nullptr));
835: PetscFunctionReturn(PETSC_SUCCESS);
836: }
838: namespace kernels
839: {
841: template <typename... Args>
842: PETSC_KERNEL_DECL static void MAXPY_kernel(const PetscInt size, PetscScalar *PETSC_RESTRICT xptr, const PetscScalar *PETSC_RESTRICT aptr, Args... yptr)
843: {
844: constexpr int N = sizeof...(Args);
845: const auto tx = threadIdx.x;
846: const PetscScalar *yptr_p[] = {yptr...};
848: PETSC_SHAREDMEM_DECL PetscScalar aptr_shmem[N];
850: // load a to shared memory
851: if (tx < N) aptr_shmem[tx] = aptr[tx];
852: __syncthreads();
854: ::Petsc::device::cupm::kernels::util::grid_stride_1D(size, [&](PetscInt i) {
855: // these may look the same but give different results!
856: #if 0
857: PetscScalar sum = 0.0;
859: #pragma unroll
860: for (auto j = 0; j < N; ++j) sum += aptr_shmem[j]*yptr_p[j][i];
861: xptr[i] += sum;
862: #else
863: auto sum = xptr[i];
865: #pragma unroll
866: for (auto j = 0; j < N; ++j) sum += aptr_shmem[j] * yptr_p[j][i];
867: xptr[i] = sum;
868: #endif
869: });
870: return;
871: }
873: } // namespace kernels
875: namespace detail
876: {
878: // a helper-struct to gobble the size_t input, it is used with template parameter pack
879: // expansion such that
880: // typename repeat_type<MyType, IdxParamPack>...
881: // expands to
882: // MyType, MyType, MyType, ... [repeated sizeof...(IdxParamPack) times]
883: template <typename T, std::size_t>
884: struct repeat_type {
885: using type = T;
886: };
888: } // namespace detail
890: template <device::cupm::DeviceType T>
891: template <std::size_t... Idx>
892: inline PetscErrorCode VecSeq_CUPM<T>::MAXPY_kernel_dispatch_(PetscDeviceContext dctx, cupmStream_t stream, PetscScalar *xptr, const PetscScalar *aptr, const Vec *yin, PetscInt size, util::index_sequence<Idx...>) noexcept
893: {
894: PetscFunctionBegin;
895: // clang-format off
896: PetscCall(
897: PetscCUPMLaunchKernel1D(
898: size, 0, stream,
899: kernels::MAXPY_kernel<typename detail::repeat_type<const PetscScalar *, Idx>::type...>,
900: size, xptr, aptr, DeviceArrayRead(dctx, yin[Idx]).data()...
901: )
902: );
903: // clang-format on
904: PetscFunctionReturn(PETSC_SUCCESS);
905: }
907: template <device::cupm::DeviceType T>
908: template <int N>
909: inline PetscErrorCode VecSeq_CUPM<T>::MAXPY_kernel_dispatch_(PetscDeviceContext dctx, cupmStream_t stream, PetscScalar *xptr, const PetscScalar *aptr, const Vec *yin, PetscInt size, PetscInt &yidx) noexcept
910: {
911: PetscFunctionBegin;
912: PetscCall(MAXPY_kernel_dispatch_(dctx, stream, xptr, aptr + yidx, yin + yidx, size, util::make_index_sequence<N>{}));
913: yidx += N;
914: PetscFunctionReturn(PETSC_SUCCESS);
915: }
917: // VecMAXPYAsync_Private
918: template <device::cupm::DeviceType T>
919: inline PetscErrorCode VecSeq_CUPM<T>::MAXPYAsync(Vec xin, PetscInt nv, const PetscScalar *alpha, Vec *yin, PetscDeviceContext dctx) noexcept
920: {
921: const auto n = xin->map->n;
922: cupmStream_t stream;
924: PetscFunctionBegin;
925: PetscCall(PetscDeviceContextGetOptionalNullContext_Internal(&dctx));
926: PetscCall(GetHandlesFrom_(dctx, &stream));
927: {
928: const auto xptr = DeviceArrayReadWrite(dctx, xin);
929: PetscScalar *d_alpha = nullptr;
930: PetscInt yidx = 0;
932: // placement of early-return is deliberate, we would like to capture the
933: // DeviceArrayReadWrite() call (which calls PetscObjectStateIncreate()) before we bail
934: if (!n || !nv) PetscFunctionReturn(PETSC_SUCCESS);
935: PetscCall(PetscDeviceMalloc(dctx, PETSC_MEMTYPE_CUPM(), nv, &d_alpha));
936: PetscCall(PetscCUPMMemcpyAsync(d_alpha, alpha, nv, cupmMemcpyHostToDevice, stream));
937: PetscCall(PetscLogGpuTimeBegin());
938: do {
939: switch (nv - yidx) {
940: case 7:
941: PetscCall(MAXPY_kernel_dispatch_<7>(dctx, stream, xptr.data(), d_alpha, yin, n, yidx));
942: break;
943: case 6:
944: PetscCall(MAXPY_kernel_dispatch_<6>(dctx, stream, xptr.data(), d_alpha, yin, n, yidx));
945: break;
946: case 5:
947: PetscCall(MAXPY_kernel_dispatch_<5>(dctx, stream, xptr.data(), d_alpha, yin, n, yidx));
948: break;
949: case 4:
950: PetscCall(MAXPY_kernel_dispatch_<4>(dctx, stream, xptr.data(), d_alpha, yin, n, yidx));
951: break;
952: case 3:
953: PetscCall(MAXPY_kernel_dispatch_<3>(dctx, stream, xptr.data(), d_alpha, yin, n, yidx));
954: break;
955: case 2:
956: PetscCall(MAXPY_kernel_dispatch_<2>(dctx, stream, xptr.data(), d_alpha, yin, n, yidx));
957: break;
958: case 1:
959: PetscCall(MAXPY_kernel_dispatch_<1>(dctx, stream, xptr.data(), d_alpha, yin, n, yidx));
960: break;
961: default: // 8 or more
962: PetscCall(MAXPY_kernel_dispatch_<8>(dctx, stream, xptr.data(), d_alpha, yin, n, yidx));
963: break;
964: }
965: } while (yidx < nv);
966: PetscCall(PetscLogGpuTimeEnd());
967: PetscCall(PetscDeviceFree(dctx, d_alpha));
968: PetscCall(PetscDeviceContextSynchronizeIfGlobalBlocking_Internal(dctx));
969: }
970: PetscCall(PetscLogGpuFlops(nv * 2 * n));
971: PetscFunctionReturn(PETSC_SUCCESS);
972: }
974: // v->ops->maxpy
975: template <device::cupm::DeviceType T>
976: inline PetscErrorCode VecSeq_CUPM<T>::MAXPY(Vec xin, PetscInt nv, const PetscScalar *alpha, Vec *yin) noexcept
977: {
978: PetscFunctionBegin;
979: PetscCall(MAXPYAsync(xin, nv, alpha, yin, nullptr));
980: PetscFunctionReturn(PETSC_SUCCESS);
981: }
983: template <device::cupm::DeviceType T>
984: inline PetscErrorCode VecSeq_CUPM<T>::Dot(Vec xin, Vec yin, PetscScalar *z) noexcept
985: {
986: PetscFunctionBegin;
987: if (const auto n = static_cast<cupmBlasInt_t>(xin->map->n)) {
988: PetscDeviceContext dctx;
989: cupmBlasHandle_t cupmBlasHandle;
991: PetscCall(GetHandles_(&dctx, &cupmBlasHandle));
992: // arguments y, x are reversed because BLAS complex conjugates the first argument, PETSc the
993: // second
994: PetscCall(PetscLogGpuTimeBegin());
995: PetscCallCUPMBLAS(cupmBlasXdot(cupmBlasHandle, n, DeviceArrayRead(dctx, yin), 1, DeviceArrayRead(dctx, xin), 1, cupmScalarPtrCast(z)));
996: PetscCall(PetscLogGpuTimeEnd());
997: PetscCall(PetscLogGpuFlops(2 * n - 1));
998: } else {
999: *z = 0.0;
1000: }
1001: PetscFunctionReturn(PETSC_SUCCESS);
1002: }
1004: #define MDOT_WORKGROUP_NUM 128
1005: #define MDOT_WORKGROUP_SIZE MDOT_WORKGROUP_NUM
1007: namespace kernels
1008: {
1010: PETSC_DEVICE_INLINE_DECL static PetscInt EntriesPerGroup(const PetscInt size) noexcept
1011: {
1012: const auto group_entries = (size - 1) / gridDim.x + 1;
1013: // for very small vectors, a group should still do some work
1014: return group_entries ? group_entries : 1;
1015: }
1017: template <typename... ConstPetscScalarPointer>
1018: PETSC_KERNEL_DECL static void MDot_kernel(const PetscScalar *PETSC_RESTRICT x, const PetscInt size, PetscScalar *PETSC_RESTRICT results, ConstPetscScalarPointer... y)
1019: {
1020: constexpr int N = sizeof...(ConstPetscScalarPointer);
1021: const PetscScalar *ylocal[] = {y...};
1022: PetscScalar sumlocal[N];
1024: PETSC_SHAREDMEM_DECL PetscScalar shmem[N * MDOT_WORKGROUP_SIZE];
1026: // HIP -- for whatever reason -- has threadIdx, blockIdx, blockDim, and gridDim as separate
1027: // types, so each of these go on separate lines...
1028: const auto tx = threadIdx.x;
1029: const auto bx = blockIdx.x;
1030: const auto bdx = blockDim.x;
1031: const auto gdx = gridDim.x;
1032: const auto worksize = EntriesPerGroup(size);
1033: const auto begin = tx + bx * worksize;
1034: const auto end = min((bx + 1) * worksize, size);
1036: #pragma unroll
1037: for (auto i = 0; i < N; ++i) sumlocal[i] = 0;
1039: for (auto i = begin; i < end; i += bdx) {
1040: const auto xi = x[i]; // load only once from global memory!
1042: #pragma unroll
1043: for (auto j = 0; j < N; ++j) sumlocal[j] += ylocal[j][i] * xi;
1044: }
1046: #pragma unroll
1047: for (auto i = 0; i < N; ++i) shmem[tx + i * MDOT_WORKGROUP_SIZE] = sumlocal[i];
1049: // parallel reduction
1050: for (auto stride = bdx / 2; stride > 0; stride /= 2) {
1051: __syncthreads();
1052: if (tx < stride) {
1053: #pragma unroll
1054: for (auto i = 0; i < N; ++i) shmem[tx + i * MDOT_WORKGROUP_SIZE] += shmem[tx + stride + i * MDOT_WORKGROUP_SIZE];
1055: }
1056: }
1057: // bottom N threads per block write to global memory
1058: // REVIEW ME: I am ~pretty~ sure we don't need another __syncthreads() here since each thread
1059: // writes to the same sections in the above loop that it is about to read from below, but
1060: // running this under the racecheck tool of cuda-memcheck reports a write-after-write hazard.
1061: __syncthreads();
1062: if (tx < N) results[bx + tx * gdx] = shmem[tx * MDOT_WORKGROUP_SIZE];
1063: return;
1064: }
1066: namespace
1067: {
1069: PETSC_KERNEL_DECL void sum_kernel(const PetscInt size, PetscScalar *PETSC_RESTRICT results)
1070: {
1071: int local_i = 0;
1072: PetscScalar local_results[8];
1074: // each thread sums up MDOT_WORKGROUP_NUM entries of the result, storing it in a local buffer
1075: //
1076: // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
1077: // | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ...
1078: // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
1079: // | ______________________________________________________/
1080: // | / <- MDOT_WORKGROUP_NUM ->
1081: // |/
1082: // +
1083: // v
1084: // *-*-*
1085: // | | | ...
1086: // *-*-*
1087: //
1088: ::Petsc::device::cupm::kernels::util::grid_stride_1D(size, [&](PetscInt i) {
1089: PetscScalar z_sum = 0;
1091: for (auto j = i * MDOT_WORKGROUP_SIZE; j < (i + 1) * MDOT_WORKGROUP_SIZE; ++j) z_sum += results[j];
1092: local_results[local_i++] = z_sum;
1093: });
1094: // if we needed more than 1 workgroup to handle the vector we should sync since other threads
1095: // may currently be reading from results
1096: if (size >= MDOT_WORKGROUP_SIZE) __syncthreads();
1097: // Local buffer is now written to global memory
1098: ::Petsc::device::cupm::kernels::util::grid_stride_1D(size, [&](PetscInt i) {
1099: const auto j = --local_i;
1101: if (j >= 0) results[i] = local_results[j];
1102: });
1103: return;
1104: }
1106: } // namespace
1108: #if PetscDefined(USING_HCC)
1109: namespace do_not_use
1110: {
1112: inline void silence_warning_function_sum_kernel_is_not_needed_and_will_not_be_emitted()
1113: {
1114: (void)sum_kernel;
1115: }
1117: } // namespace do_not_use
1118: #endif
1120: } // namespace kernels
1122: template <device::cupm::DeviceType T>
1123: template <std::size_t... Idx>
1124: inline PetscErrorCode VecSeq_CUPM<T>::MDot_kernel_dispatch_(PetscDeviceContext dctx, cupmStream_t stream, const PetscScalar *xarr, const Vec yin[], PetscInt size, PetscScalar *results, util::index_sequence<Idx...>) noexcept
1125: {
1126: PetscFunctionBegin;
1127: // REVIEW ME: convert this kernel launch to PetscCUPMLaunchKernel1D(), it currently launches
1128: // 128 blocks of 128 threads every time which may be wasteful
1129: // clang-format off
1130: PetscCallCUPM(
1131: cupmLaunchKernel(
1132: kernels::MDot_kernel<typename detail::repeat_type<const PetscScalar *, Idx>::type...>,
1133: MDOT_WORKGROUP_NUM, MDOT_WORKGROUP_SIZE, 0, stream,
1134: xarr, size, results, DeviceArrayRead(dctx, yin[Idx]).data()...
1135: )
1136: );
1137: // clang-format on
1138: PetscFunctionReturn(PETSC_SUCCESS);
1139: }
1141: template <device::cupm::DeviceType T>
1142: template <int N>
1143: inline PetscErrorCode VecSeq_CUPM<T>::MDot_kernel_dispatch_(PetscDeviceContext dctx, cupmStream_t stream, const PetscScalar *xarr, const Vec yin[], PetscInt size, PetscScalar *results, PetscInt &yidx) noexcept
1144: {
1145: PetscFunctionBegin;
1146: PetscCall(MDot_kernel_dispatch_(dctx, stream, xarr, yin + yidx, size, results + yidx * MDOT_WORKGROUP_NUM, util::make_index_sequence<N>{}));
1147: yidx += N;
1148: PetscFunctionReturn(PETSC_SUCCESS);
1149: }
1151: template <device::cupm::DeviceType T>
1152: inline PetscErrorCode VecSeq_CUPM<T>::MDot_(std::false_type, Vec xin, PetscInt nv, const Vec yin[], PetscScalar *z, PetscDeviceContext dctx) noexcept
1153: {
1154: // the largest possible size of a batch
1155: constexpr PetscInt batchsize = 8;
1156: // how many sub streams to create, if nv <= batchsize we can do this without looping, so we
1157: // do not create substreams. Note we don't create more than 8 streams, in practice we could
1158: // not get more parallelism with higher numbers.
1159: const auto num_sub_streams = nv > batchsize ? std::min((nv + batchsize) / batchsize, batchsize) : 0;
1160: const auto n = xin->map->n;
1161: // number of vectors that we handle via the batches. note any singletons are handled by
1162: // cublas, hence the nv-1.
1163: const auto nvbatch = ((nv % batchsize) == 1) ? nv - 1 : nv;
1164: const auto nwork = nvbatch * MDOT_WORKGROUP_NUM;
1165: PetscScalar *d_results;
1166: cupmStream_t stream;
1168: PetscFunctionBegin;
1169: PetscCall(GetHandlesFrom_(dctx, &stream));
1170: // allocate scratchpad memory for the results of individual work groups
1171: PetscCall(PetscDeviceMalloc(dctx, PETSC_MEMTYPE_CUPM(), nwork, &d_results));
1172: {
1173: const auto xptr = DeviceArrayRead(dctx, xin);
1174: PetscInt yidx = 0;
1175: auto subidx = 0;
1176: auto cur_stream = stream;
1177: auto cur_ctx = dctx;
1178: PetscDeviceContext *sub = nullptr;
1179: PetscStreamType stype;
1181: // REVIEW ME: maybe PetscDeviceContextFork() should insert dctx into the first entry of
1182: // sub. Ideally the parent context should also join in on the fork, but it is extremely
1183: // fiddly to do so presently
1184: PetscCall(PetscDeviceContextGetStreamType(dctx, &stype));
1185: if (stype == PETSC_STREAM_GLOBAL_BLOCKING) stype = PETSC_STREAM_DEFAULT_BLOCKING;
1186: // If we have a globally blocking stream create nonblocking streams instead (as we can
1187: // locally exploit the parallelism). Otherwise use the prescribed stream type.
1188: PetscCall(PetscDeviceContextForkWithStreamType(dctx, stype, num_sub_streams, &sub));
1189: PetscCall(PetscLogGpuTimeBegin());
1190: do {
1191: if (num_sub_streams) {
1192: cur_ctx = sub[subidx++ % num_sub_streams];
1193: PetscCall(GetHandlesFrom_(cur_ctx, &cur_stream));
1194: }
1195: // REVIEW ME: Should probably try and load-balance these. Consider the case where nv = 9;
1196: // it is very likely better to do 4+5 rather than 8+1
1197: switch (nv - yidx) {
1198: case 7:
1199: PetscCall(MDot_kernel_dispatch_<7>(cur_ctx, cur_stream, xptr.data(), yin, n, d_results, yidx));
1200: break;
1201: case 6:
1202: PetscCall(MDot_kernel_dispatch_<6>(cur_ctx, cur_stream, xptr.data(), yin, n, d_results, yidx));
1203: break;
1204: case 5:
1205: PetscCall(MDot_kernel_dispatch_<5>(cur_ctx, cur_stream, xptr.data(), yin, n, d_results, yidx));
1206: break;
1207: case 4:
1208: PetscCall(MDot_kernel_dispatch_<4>(cur_ctx, cur_stream, xptr.data(), yin, n, d_results, yidx));
1209: break;
1210: case 3:
1211: PetscCall(MDot_kernel_dispatch_<3>(cur_ctx, cur_stream, xptr.data(), yin, n, d_results, yidx));
1212: break;
1213: case 2:
1214: PetscCall(MDot_kernel_dispatch_<2>(cur_ctx, cur_stream, xptr.data(), yin, n, d_results, yidx));
1215: break;
1216: case 1: {
1217: cupmBlasHandle_t cupmBlasHandle;
1219: PetscCall(GetHandlesFrom_(cur_ctx, &cupmBlasHandle));
1220: PetscCallCUPMBLAS(cupmBlasXdot(cupmBlasHandle, static_cast<cupmBlasInt_t>(n), DeviceArrayRead(cur_ctx, yin[yidx]).cupmdata(), 1, xptr.cupmdata(), 1, cupmScalarPtrCast(z + yidx)));
1221: ++yidx;
1222: } break;
1223: default: // 8 or more
1224: PetscCall(MDot_kernel_dispatch_<8>(cur_ctx, cur_stream, xptr.data(), yin, n, d_results, yidx));
1225: break;
1226: }
1227: } while (yidx < nv);
1228: PetscCall(PetscLogGpuTimeEnd());
1229: PetscCall(PetscDeviceContextJoin(dctx, num_sub_streams, PETSC_DEVICE_CONTEXT_JOIN_DESTROY, &sub));
1230: }
1232: PetscCall(PetscCUPMLaunchKernel1D(nvbatch, 0, stream, kernels::sum_kernel, nvbatch, d_results));
1233: // copy result of device reduction to host
1234: PetscCall(PetscCUPMMemcpyAsync(z, d_results, nvbatch, cupmMemcpyDeviceToHost, stream));
1235: // do these now while final reduction is in flight
1236: PetscCall(PetscLogGpuFlops(nwork));
1237: PetscCall(PetscDeviceFree(dctx, d_results));
1238: PetscFunctionReturn(PETSC_SUCCESS);
1239: }
1241: #undef MDOT_WORKGROUP_NUM
1242: #undef MDOT_WORKGROUP_SIZE
1244: template <device::cupm::DeviceType T>
1245: inline PetscErrorCode VecSeq_CUPM<T>::MDot_(std::true_type, Vec xin, PetscInt nv, const Vec yin[], PetscScalar *z, PetscDeviceContext dctx) noexcept
1246: {
1247: // probably not worth it to run more than 8 of these at a time?
1248: const auto n_sub = PetscMin(nv, 8);
1249: const auto n = static_cast<cupmBlasInt_t>(xin->map->n);
1250: const auto xptr = DeviceArrayRead(dctx, xin);
1251: PetscScalar *d_z;
1252: PetscDeviceContext *subctx;
1253: cupmStream_t stream;
1255: PetscFunctionBegin;
1256: PetscCall(GetHandlesFrom_(dctx, &stream));
1257: PetscCall(PetscDeviceMalloc(dctx, PETSC_MEMTYPE_CUPM(), nv, &d_z));
1258: PetscCall(PetscDeviceContextFork(dctx, n_sub, &subctx));
1259: PetscCall(PetscLogGpuTimeBegin());
1260: for (PetscInt i = 0; i < nv; ++i) {
1261: const auto sub = subctx[i % n_sub];
1262: cupmBlasHandle_t handle;
1263: cupmBlasPointerMode_t old_mode;
1265: PetscCall(GetHandlesFrom_(sub, &handle));
1266: PetscCallCUPMBLAS(cupmBlasGetPointerMode(handle, &old_mode));
1267: if (old_mode != CUPMBLAS_POINTER_MODE_DEVICE) PetscCallCUPMBLAS(cupmBlasSetPointerMode(handle, CUPMBLAS_POINTER_MODE_DEVICE));
1268: PetscCallCUPMBLAS(cupmBlasXdot(handle, n, DeviceArrayRead(sub, yin[i]), 1, xptr.cupmdata(), 1, cupmScalarPtrCast(d_z + i)));
1269: if (old_mode != CUPMBLAS_POINTER_MODE_DEVICE) PetscCallCUPMBLAS(cupmBlasSetPointerMode(handle, old_mode));
1270: }
1271: PetscCall(PetscLogGpuTimeEnd());
1272: PetscCall(PetscDeviceContextJoin(dctx, n_sub, PETSC_DEVICE_CONTEXT_JOIN_DESTROY, &subctx));
1273: PetscCall(PetscCUPMMemcpyAsync(z, d_z, nv, cupmMemcpyDeviceToHost, stream));
1274: PetscCall(PetscDeviceFree(dctx, d_z));
1275: // REVIEW ME: flops?????
1276: PetscFunctionReturn(PETSC_SUCCESS);
1277: }
1279: // v->ops->mdot
1280: template <device::cupm::DeviceType T>
1281: inline PetscErrorCode VecSeq_CUPM<T>::MDot(Vec xin, PetscInt nv, const Vec yin[], PetscScalar *z) noexcept
1282: {
1283: PetscFunctionBegin;
1284: if (PetscUnlikely(nv == 1)) {
1285: // dot handles nv = 0 correctly
1286: PetscCall(Dot(xin, const_cast<Vec>(yin[0]), z));
1287: } else if (const auto n = xin->map->n) {
1288: PetscDeviceContext dctx;
1290: PetscCheck(nv > 0, PETSC_COMM_SELF, PETSC_ERR_LIB, "Number of vectors provided to %s %" PetscInt_FMT " not positive", PETSC_FUNCTION_NAME, nv);
1291: PetscCall(GetHandles_(&dctx));
1292: PetscCall(MDot_(std::integral_constant<bool, PetscDefined(USE_COMPLEX)>{}, xin, nv, yin, z, dctx));
1293: // REVIEW ME: double count of flops??
1294: PetscCall(PetscLogGpuFlops(nv * (2 * n - 1)));
1295: PetscCall(PetscDeviceContextSynchronize(dctx));
1296: } else {
1297: PetscCall(PetscArrayzero(z, nv));
1298: }
1299: PetscFunctionReturn(PETSC_SUCCESS);
1300: }
1302: // VecSetAsync_Private
1303: template <device::cupm::DeviceType T>
1304: inline PetscErrorCode VecSeq_CUPM<T>::SetAsync(Vec xin, PetscScalar alpha, PetscDeviceContext dctx) noexcept
1305: {
1306: const auto n = xin->map->n;
1307: cupmStream_t stream;
1309: PetscFunctionBegin;
1310: PetscCall(PetscDeviceContextGetOptionalNullContext_Internal(&dctx));
1311: PetscCall(GetHandlesFrom_(dctx, &stream));
1312: {
1313: const auto xptr = DeviceArrayWrite(dctx, xin);
1315: if (alpha == PetscScalar(0.0)) {
1316: PetscCall(PetscCUPMMemsetAsync(xptr.data(), 0, n, stream));
1317: } else {
1318: const auto dptr = thrust::device_pointer_cast(xptr.data());
1320: PetscCallThrust(THRUST_CALL(thrust::fill, stream, dptr, dptr + n, alpha));
1321: }
1322: }
1323: if (n > 0) PetscCall(PetscDeviceContextSynchronizeIfGlobalBlocking_Internal(dctx));
1324: PetscFunctionReturn(PETSC_SUCCESS);
1325: }
1327: // v->ops->set
1328: template <device::cupm::DeviceType T>
1329: inline PetscErrorCode VecSeq_CUPM<T>::Set(Vec xin, PetscScalar alpha) noexcept
1330: {
1331: PetscFunctionBegin;
1332: PetscCall(SetAsync(xin, alpha, nullptr));
1333: PetscFunctionReturn(PETSC_SUCCESS);
1334: }
1336: // VecScaleAsync_Private
1337: template <device::cupm::DeviceType T>
1338: inline PetscErrorCode VecSeq_CUPM<T>::ScaleAsync(Vec xin, PetscScalar alpha, PetscDeviceContext dctx) noexcept
1339: {
1340: PetscFunctionBegin;
1341: if (PetscUnlikely(alpha == PetscScalar(1.0))) PetscFunctionReturn(PETSC_SUCCESS);
1342: PetscCall(PetscDeviceContextGetOptionalNullContext_Internal(&dctx));
1343: if (PetscUnlikely(alpha == PetscScalar(0.0))) {
1344: PetscCall(SetAsync(xin, alpha, dctx));
1345: } else if (const auto n = static_cast<cupmBlasInt_t>(xin->map->n)) {
1346: cupmBlasHandle_t cupmBlasHandle;
1348: PetscCall(GetHandlesFrom_(dctx, &cupmBlasHandle));
1349: PetscCall(PetscLogGpuTimeBegin());
1350: PetscCallCUPMBLAS(cupmBlasXscal(cupmBlasHandle, n, cupmScalarPtrCast(&alpha), DeviceArrayReadWrite(dctx, xin), 1));
1351: PetscCall(PetscLogGpuTimeEnd());
1352: PetscCall(PetscLogGpuFlops(n));
1353: PetscCall(PetscDeviceContextSynchronizeIfGlobalBlocking_Internal(dctx));
1354: } else {
1355: PetscCall(MaybeIncrementEmptyLocalVec(xin));
1356: }
1357: PetscFunctionReturn(PETSC_SUCCESS);
1358: }
1360: // v->ops->scale
1361: template <device::cupm::DeviceType T>
1362: inline PetscErrorCode VecSeq_CUPM<T>::Scale(Vec xin, PetscScalar alpha) noexcept
1363: {
1364: PetscFunctionBegin;
1365: PetscCall(ScaleAsync(xin, alpha, nullptr));
1366: PetscFunctionReturn(PETSC_SUCCESS);
1367: }
1369: // v->ops->tdot
1370: template <device::cupm::DeviceType T>
1371: inline PetscErrorCode VecSeq_CUPM<T>::TDot(Vec xin, Vec yin, PetscScalar *z) noexcept
1372: {
1373: PetscFunctionBegin;
1374: if (const auto n = static_cast<cupmBlasInt_t>(xin->map->n)) {
1375: PetscDeviceContext dctx;
1376: cupmBlasHandle_t cupmBlasHandle;
1378: PetscCall(GetHandles_(&dctx, &cupmBlasHandle));
1379: PetscCall(PetscLogGpuTimeBegin());
1380: PetscCallCUPMBLAS(cupmBlasXdotu(cupmBlasHandle, n, DeviceArrayRead(dctx, xin), 1, DeviceArrayRead(dctx, yin), 1, cupmScalarPtrCast(z)));
1381: PetscCall(PetscLogGpuTimeEnd());
1382: PetscCall(PetscLogGpuFlops(2 * n - 1));
1383: } else {
1384: *z = 0.0;
1385: }
1386: PetscFunctionReturn(PETSC_SUCCESS);
1387: }
1389: // VecCopyAsync_Private
1390: template <device::cupm::DeviceType T>
1391: inline PetscErrorCode VecSeq_CUPM<T>::CopyAsync(Vec xin, Vec yout, PetscDeviceContext dctx) noexcept
1392: {
1393: PetscFunctionBegin;
1394: if (xin == yout) PetscFunctionReturn(PETSC_SUCCESS);
1395: if (const auto n = xin->map->n) {
1396: const auto xmask = xin->offloadmask;
1397: // silence buggy gcc warning: mode may be used uninitialized in this function
1398: auto mode = cupmMemcpyDeviceToDevice;
1399: cupmStream_t stream;
1401: // translate from PetscOffloadMask to cupmMemcpyKind
1402: PetscCall(PetscDeviceContextGetOptionalNullContext_Internal(&dctx));
1403: switch (const auto ymask = yout->offloadmask) {
1404: case PETSC_OFFLOAD_UNALLOCATED: {
1405: PetscBool yiscupm;
1407: PetscCall(PetscObjectTypeCompareAny(PetscObjectCast(yout), &yiscupm, VECSEQCUPM(), VECMPICUPM(), ""));
1408: if (yiscupm) {
1409: mode = PetscOffloadDevice(xmask) ? cupmMemcpyDeviceToDevice : cupmMemcpyHostToHost;
1410: break;
1411: }
1412: } // fall-through if unallocated and not cupm
1413: #if PETSC_CPP_VERSION >= 17
1414: [[fallthrough]];
1415: #endif
1416: case PETSC_OFFLOAD_CPU:
1417: mode = PetscOffloadHost(xmask) ? cupmMemcpyHostToHost : cupmMemcpyDeviceToHost;
1418: break;
1419: case PETSC_OFFLOAD_BOTH:
1420: case PETSC_OFFLOAD_GPU:
1421: mode = PetscOffloadDevice(xmask) ? cupmMemcpyDeviceToDevice : cupmMemcpyHostToDevice;
1422: break;
1423: default:
1424: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Incompatible offload mask %s", PetscOffloadMaskToString(ymask));
1425: }
1427: PetscCall(GetHandlesFrom_(dctx, &stream));
1428: switch (mode) {
1429: case cupmMemcpyDeviceToDevice: // the best case
1430: case cupmMemcpyHostToDevice: { // not terrible
1431: const auto yptr = DeviceArrayWrite(dctx, yout);
1432: const auto xptr = mode == cupmMemcpyDeviceToDevice ? DeviceArrayRead(dctx, xin).data() : HostArrayRead(dctx, xin).data();
1434: PetscCall(PetscLogGpuTimeBegin());
1435: PetscCall(PetscCUPMMemcpyAsync(yptr.data(), xptr, n, mode, stream));
1436: PetscCall(PetscLogGpuTimeEnd());
1437: } break;
1438: case cupmMemcpyDeviceToHost: // not great
1439: case cupmMemcpyHostToHost: { // worst case
1440: const auto xptr = mode == cupmMemcpyDeviceToHost ? DeviceArrayRead(dctx, xin).data() : HostArrayRead(dctx, xin).data();
1441: PetscScalar *yptr;
1443: PetscCall(VecGetArrayWrite(yout, &yptr));
1444: if (mode == cupmMemcpyDeviceToHost) PetscCall(PetscLogGpuTimeBegin());
1445: PetscCall(PetscCUPMMemcpyAsync(yptr, xptr, n, mode, stream, /* force async */ true));
1446: if (mode == cupmMemcpyDeviceToHost) PetscCall(PetscLogGpuTimeEnd());
1447: PetscCall(VecRestoreArrayWrite(yout, &yptr));
1448: } break;
1449: default:
1450: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_GPU, "Unknown cupmMemcpyKind %d", static_cast<int>(mode));
1451: }
1452: PetscCall(PetscDeviceContextSynchronizeIfGlobalBlocking_Internal(dctx));
1453: } else {
1454: PetscCall(MaybeIncrementEmptyLocalVec(yout));
1455: }
1456: PetscFunctionReturn(PETSC_SUCCESS);
1457: }
1459: // v->ops->copy
1460: template <device::cupm::DeviceType T>
1461: inline PetscErrorCode VecSeq_CUPM<T>::Copy(Vec xin, Vec yout) noexcept
1462: {
1463: PetscFunctionBegin;
1464: PetscCall(CopyAsync(xin, yout, nullptr));
1465: PetscFunctionReturn(PETSC_SUCCESS);
1466: }
1468: // VecSwapAsync_Private
1469: template <device::cupm::DeviceType T>
1470: inline PetscErrorCode VecSeq_CUPM<T>::SwapAsync(Vec xin, Vec yin, PetscDeviceContext dctx) noexcept
1471: {
1472: PetscFunctionBegin;
1473: if (xin == yin) PetscFunctionReturn(PETSC_SUCCESS);
1474: PetscCall(PetscDeviceContextGetOptionalNullContext_Internal(&dctx));
1475: if (const auto n = static_cast<cupmBlasInt_t>(xin->map->n)) {
1476: cupmBlasHandle_t cupmBlasHandle;
1478: PetscCall(GetHandlesFrom_(dctx, &cupmBlasHandle));
1479: PetscCall(PetscLogGpuTimeBegin());
1480: PetscCallCUPMBLAS(cupmBlasXswap(cupmBlasHandle, n, DeviceArrayReadWrite(dctx, xin), 1, DeviceArrayReadWrite(dctx, yin), 1));
1481: PetscCall(PetscLogGpuTimeEnd());
1482: PetscCall(PetscDeviceContextSynchronizeIfGlobalBlocking_Internal(dctx));
1483: } else {
1484: PetscCall(MaybeIncrementEmptyLocalVec(xin));
1485: PetscCall(MaybeIncrementEmptyLocalVec(yin));
1486: }
1487: PetscFunctionReturn(PETSC_SUCCESS);
1488: }
1490: // v->ops->swap
1491: template <device::cupm::DeviceType T>
1492: inline PetscErrorCode VecSeq_CUPM<T>::Swap(Vec xin, Vec yin) noexcept
1493: {
1494: PetscFunctionBegin;
1495: PetscCall(SwapAsync(xin, yin, nullptr));
1496: PetscFunctionReturn(PETSC_SUCCESS);
1497: }
1499: // VecAXPYBYAsync_Private
1500: template <device::cupm::DeviceType T>
1501: inline PetscErrorCode VecSeq_CUPM<T>::AXPBYAsync(Vec yin, PetscScalar alpha, PetscScalar beta, Vec xin, PetscDeviceContext dctx) noexcept
1502: {
1503: PetscFunctionBegin;
1504: PetscCall(PetscDeviceContextGetOptionalNullContext_Internal(&dctx));
1505: if (alpha == PetscScalar(0.0)) {
1506: PetscCall(ScaleAsync(yin, beta, dctx));
1507: } else if (beta == PetscScalar(1.0)) {
1508: PetscCall(AXPYAsync(yin, alpha, xin, dctx));
1509: } else if (alpha == PetscScalar(1.0)) {
1510: PetscCall(AYPXAsync(yin, beta, xin, dctx));
1511: } else if (const auto n = static_cast<cupmBlasInt_t>(yin->map->n)) {
1512: const auto betaIsZero = beta == PetscScalar(0.0);
1513: const auto aptr = cupmScalarPtrCast(&alpha);
1514: cupmBlasHandle_t cupmBlasHandle;
1516: PetscCall(GetHandlesFrom_(dctx, &cupmBlasHandle));
1517: {
1518: const auto xptr = DeviceArrayRead(dctx, xin);
1520: if (betaIsZero /* beta = 0 */) {
1521: // here we can get away with purely write-only as we memcpy into it first
1522: const auto yptr = DeviceArrayWrite(dctx, yin);
1523: cupmStream_t stream;
1525: PetscCall(GetHandlesFrom_(dctx, &stream));
1526: PetscCall(PetscLogGpuTimeBegin());
1527: PetscCall(PetscCUPMMemcpyAsync(yptr.data(), xptr.data(), n, cupmMemcpyDeviceToDevice, stream));
1528: PetscCallCUPMBLAS(cupmBlasXscal(cupmBlasHandle, n, aptr, yptr.cupmdata(), 1));
1529: } else {
1530: const auto yptr = DeviceArrayReadWrite(dctx, yin);
1532: PetscCall(PetscLogGpuTimeBegin());
1533: PetscCallCUPMBLAS(cupmBlasXscal(cupmBlasHandle, n, cupmScalarPtrCast(&beta), yptr.cupmdata(), 1));
1534: PetscCallCUPMBLAS(cupmBlasXaxpy(cupmBlasHandle, n, aptr, xptr.cupmdata(), 1, yptr.cupmdata(), 1));
1535: }
1536: }
1537: PetscCall(PetscLogGpuTimeEnd());
1538: PetscCall(PetscLogGpuFlops((betaIsZero ? 1 : 3) * n));
1539: PetscCall(PetscDeviceContextSynchronizeIfGlobalBlocking_Internal(dctx));
1540: } else {
1541: PetscCall(MaybeIncrementEmptyLocalVec(yin));
1542: }
1543: PetscFunctionReturn(PETSC_SUCCESS);
1544: }
1546: // v->ops->axpby
1547: template <device::cupm::DeviceType T>
1548: inline PetscErrorCode VecSeq_CUPM<T>::AXPBY(Vec yin, PetscScalar alpha, PetscScalar beta, Vec xin) noexcept
1549: {
1550: PetscFunctionBegin;
1551: PetscCall(AXPBYAsync(yin, alpha, beta, xin, nullptr));
1552: PetscFunctionReturn(PETSC_SUCCESS);
1553: }
1555: // VecAXPBYPCZAsync_Private
1556: template <device::cupm::DeviceType T>
1557: inline PetscErrorCode VecSeq_CUPM<T>::AXPBYPCZAsync(Vec zin, PetscScalar alpha, PetscScalar beta, PetscScalar gamma, Vec xin, Vec yin, PetscDeviceContext dctx) noexcept
1558: {
1559: PetscFunctionBegin;
1560: PetscCall(PetscDeviceContextGetOptionalNullContext_Internal(&dctx));
1561: if (gamma != PetscScalar(1.0)) PetscCall(ScaleAsync(zin, gamma, dctx));
1562: PetscCall(AXPYAsync(zin, alpha, xin, dctx));
1563: PetscCall(AXPYAsync(zin, beta, yin, dctx));
1564: PetscFunctionReturn(PETSC_SUCCESS);
1565: }
1567: // v->ops->axpbypcz
1568: template <device::cupm::DeviceType T>
1569: inline PetscErrorCode VecSeq_CUPM<T>::AXPBYPCZ(Vec zin, PetscScalar alpha, PetscScalar beta, PetscScalar gamma, Vec xin, Vec yin) noexcept
1570: {
1571: PetscFunctionBegin;
1572: PetscCall(AXPBYPCZAsync(zin, alpha, beta, gamma, xin, yin, nullptr));
1573: PetscFunctionReturn(PETSC_SUCCESS);
1574: }
1576: // v->ops->norm
1577: template <device::cupm::DeviceType T>
1578: inline PetscErrorCode VecSeq_CUPM<T>::Norm(Vec xin, NormType type, PetscReal *z) noexcept
1579: {
1580: PetscDeviceContext dctx;
1581: cupmBlasHandle_t cupmBlasHandle;
1583: PetscFunctionBegin;
1584: PetscCall(GetHandles_(&dctx, &cupmBlasHandle));
1585: if (const auto n = static_cast<cupmBlasInt_t>(xin->map->n)) {
1586: const auto xptr = DeviceArrayRead(dctx, xin);
1587: PetscInt flopCount = 0;
1589: PetscCall(PetscLogGpuTimeBegin());
1590: switch (type) {
1591: case NORM_1_AND_2:
1592: case NORM_1:
1593: PetscCallCUPMBLAS(cupmBlasXasum(cupmBlasHandle, n, xptr.cupmdata(), 1, cupmRealPtrCast(z)));
1594: flopCount = std::max(n - 1, 0);
1595: if (type == NORM_1) break;
1596: ++z; // fall-through
1597: #if PETSC_CPP_VERSION >= 17
1598: [[fallthrough]];
1599: #endif
1600: case NORM_2:
1601: case NORM_FROBENIUS:
1602: PetscCallCUPMBLAS(cupmBlasXnrm2(cupmBlasHandle, n, xptr.cupmdata(), 1, cupmRealPtrCast(z)));
1603: flopCount += std::max(2 * n - 1, 0); // += in case we've fallen through from NORM_1_AND_2
1604: break;
1605: case NORM_INFINITY: {
1606: cupmBlasInt_t max_loc = 0;
1607: PetscScalar xv = 0.;
1608: cupmStream_t stream;
1610: PetscCall(GetHandlesFrom_(dctx, &stream));
1611: PetscCallCUPMBLAS(cupmBlasXamax(cupmBlasHandle, n, xptr.cupmdata(), 1, &max_loc));
1612: PetscCall(PetscCUPMMemcpyAsync(&xv, xptr.data() + max_loc - 1, 1, cupmMemcpyDeviceToHost, stream));
1613: *z = PetscAbsScalar(xv);
1614: // REVIEW ME: flopCount = ???
1615: } break;
1616: }
1617: PetscCall(PetscLogGpuTimeEnd());
1618: PetscCall(PetscLogGpuFlops(flopCount));
1619: } else {
1620: z[0] = 0.0;
1621: z[type == NORM_1_AND_2] = 0.0;
1622: }
1623: PetscFunctionReturn(PETSC_SUCCESS);
1624: }
1626: namespace detail
1627: {
1629: template <NormType wnormtype>
1630: class ErrorWNormTransformBase {
1631: public:
1632: using result_type = thrust::tuple<PetscReal, PetscReal, PetscReal, PetscInt, PetscInt, PetscInt>;
1634: constexpr explicit ErrorWNormTransformBase(PetscReal v) noexcept : ignore_max_{v} { }
1636: protected:
1637: struct NormTuple {
1638: PetscReal norm;
1639: PetscInt loc;
1640: };
1642: PETSC_NODISCARD PETSC_HOSTDEVICE_INLINE_DECL static NormTuple compute_norm_(PetscReal err, PetscReal tol) noexcept
1643: {
1644: if (tol > 0.) {
1645: const auto val = err / tol;
1647: return {wnormtype == NORM_INFINITY ? val : PetscSqr(val), 1};
1648: } else {
1649: return {0.0, 0};
1650: }
1651: }
1653: PetscReal ignore_max_;
1654: };
1656: template <NormType wnormtype>
1657: struct ErrorWNormTransform : ErrorWNormTransformBase<wnormtype> {
1658: using base_type = ErrorWNormTransformBase<wnormtype>;
1659: using result_type = typename base_type::result_type;
1660: using argument_type = thrust::tuple<PetscScalar, PetscScalar, PetscScalar, PetscScalar>;
1662: using base_type::base_type;
1664: PETSC_NODISCARD PETSC_HOSTDEVICE_INLINE_DECL result_type operator()(const argument_type &x) const noexcept
1665: {
1666: const auto u = thrust::get<0>(x); // with x.get<0>(), cuda-12.4.0 gives error: class "cuda::std::__4::tuple<PetscScalar, PetscScalar, PetscScalar, PetscScalar>" has no member "get"
1667: const auto y = thrust::get<1>(x);
1668: const auto au = PetscAbsScalar(u);
1669: const auto ay = PetscAbsScalar(y);
1670: const auto skip = au < this->ignore_max_ || ay < this->ignore_max_;
1671: const auto tola = skip ? 0.0 : PetscRealPart(thrust::get<2>(x));
1672: const auto tolr = skip ? 0.0 : PetscRealPart(thrust::get<3>(x)) * PetscMax(au, ay);
1673: const auto tol = tola + tolr;
1674: const auto err = PetscAbsScalar(u - y);
1675: const auto tup_a = this->compute_norm_(err, tola);
1676: const auto tup_r = this->compute_norm_(err, tolr);
1677: const auto tup_n = this->compute_norm_(err, tol);
1679: return {tup_n.norm, tup_a.norm, tup_r.norm, tup_n.loc, tup_a.loc, tup_r.loc};
1680: }
1681: };
1683: template <NormType wnormtype>
1684: struct ErrorWNormETransform : ErrorWNormTransformBase<wnormtype> {
1685: using base_type = ErrorWNormTransformBase<wnormtype>;
1686: using result_type = typename base_type::result_type;
1687: using argument_type = thrust::tuple<PetscScalar, PetscScalar, PetscScalar, PetscScalar, PetscScalar>;
1689: using base_type::base_type;
1691: PETSC_NODISCARD PETSC_HOSTDEVICE_INLINE_DECL result_type operator()(const argument_type &x) const noexcept
1692: {
1693: const auto au = PetscAbsScalar(thrust::get<0>(x));
1694: const auto ay = PetscAbsScalar(thrust::get<1>(x));
1695: const auto skip = au < this->ignore_max_ || ay < this->ignore_max_;
1696: const auto tola = skip ? 0.0 : PetscRealPart(thrust::get<3>(x));
1697: const auto tolr = skip ? 0.0 : PetscRealPart(thrust::get<4>(x)) * PetscMax(au, ay);
1698: const auto tol = tola + tolr;
1699: const auto err = PetscAbsScalar(thrust::get<2>(x));
1700: const auto tup_a = this->compute_norm_(err, tola);
1701: const auto tup_r = this->compute_norm_(err, tolr);
1702: const auto tup_n = this->compute_norm_(err, tol);
1704: return {tup_n.norm, tup_a.norm, tup_r.norm, tup_n.loc, tup_a.loc, tup_r.loc};
1705: }
1706: };
1708: template <NormType wnormtype>
1709: struct ErrorWNormReduce {
1710: using value_type = typename ErrorWNormTransformBase<wnormtype>::result_type;
1712: PETSC_NODISCARD PETSC_HOSTDEVICE_INLINE_DECL value_type operator()(const value_type &lhs, const value_type &rhs) const noexcept
1713: {
1714: // cannot use lhs.get<0>() etc since the using decl above ambiguates the fact that
1715: // result_type is a template, so in order to fix this we would need to write:
1716: //
1717: // lhs.template get<0>()
1718: //
1719: // which is unseemly.
1720: if (wnormtype == NORM_INFINITY) {
1721: // clang-format off
1722: return {
1723: PetscMax(thrust::get<0>(lhs), thrust::get<0>(rhs)),
1724: PetscMax(thrust::get<1>(lhs), thrust::get<1>(rhs)),
1725: PetscMax(thrust::get<2>(lhs), thrust::get<2>(rhs)),
1726: thrust::get<3>(lhs) + thrust::get<3>(rhs),
1727: thrust::get<4>(lhs) + thrust::get<4>(rhs),
1728: thrust::get<5>(lhs) + thrust::get<5>(rhs)
1729: };
1730: // clang-format on
1731: } else {
1732: // clang-format off
1733: return {
1734: thrust::get<0>(lhs) + thrust::get<0>(rhs),
1735: thrust::get<1>(lhs) + thrust::get<1>(rhs),
1736: thrust::get<2>(lhs) + thrust::get<2>(rhs),
1737: thrust::get<3>(lhs) + thrust::get<3>(rhs),
1738: thrust::get<4>(lhs) + thrust::get<4>(rhs),
1739: thrust::get<5>(lhs) + thrust::get<5>(rhs)
1740: };
1741: // clang-format on
1742: }
1743: }
1744: };
1746: template <template <NormType> class WNormTransformType, typename Tuple, typename cupmStream_t>
1747: inline PetscErrorCode ExecuteWNorm(Tuple &&first, Tuple &&last, NormType wnormtype, cupmStream_t stream, PetscReal ignore_max, PetscReal *norm, PetscInt *norm_loc, PetscReal *norma, PetscInt *norma_loc, PetscReal *normr, PetscInt *normr_loc) noexcept
1748: {
1749: auto begin = thrust::make_zip_iterator(std::forward<Tuple>(first));
1750: auto end = thrust::make_zip_iterator(std::forward<Tuple>(last));
1751: PetscReal n = 0, na = 0, nr = 0;
1752: PetscInt n_loc = 0, na_loc = 0, nr_loc = 0;
1754: PetscFunctionBegin;
1755: // clang-format off
1756: if (wnormtype == NORM_INFINITY) {
1757: PetscCallThrust(
1758: thrust::tie(*norm, *norma, *normr, *norm_loc, *norma_loc, *normr_loc) = THRUST_CALL(
1759: thrust::transform_reduce,
1760: stream,
1761: std::move(begin),
1762: std::move(end),
1763: WNormTransformType<NORM_INFINITY>{ignore_max},
1764: thrust::make_tuple(n, na, nr, n_loc, na_loc, nr_loc),
1765: ErrorWNormReduce<NORM_INFINITY>{}
1766: )
1767: );
1768: } else {
1769: PetscCallThrust(
1770: thrust::tie(*norm, *norma, *normr, *norm_loc, *norma_loc, *normr_loc) = THRUST_CALL(
1771: thrust::transform_reduce,
1772: stream,
1773: std::move(begin),
1774: std::move(end),
1775: WNormTransformType<NORM_2>{ignore_max},
1776: thrust::make_tuple(n, na, nr, n_loc, na_loc, nr_loc),
1777: ErrorWNormReduce<NORM_2>{}
1778: )
1779: );
1780: }
1781: // clang-format on
1782: if (wnormtype == NORM_2) {
1783: *norm = PetscSqrtReal(*norm);
1784: *norma = PetscSqrtReal(*norma);
1785: *normr = PetscSqrtReal(*normr);
1786: }
1787: PetscFunctionReturn(PETSC_SUCCESS);
1788: }
1790: } // namespace detail
1792: // v->ops->errorwnorm
1793: template <device::cupm::DeviceType T>
1794: inline PetscErrorCode VecSeq_CUPM<T>::ErrorWnorm(Vec U, Vec Y, Vec E, NormType wnormtype, PetscReal atol, Vec vatol, PetscReal rtol, Vec vrtol, PetscReal ignore_max, PetscReal *norm, PetscInt *norm_loc, PetscReal *norma, PetscInt *norma_loc, PetscReal *normr, PetscInt *normr_loc) noexcept
1795: {
1796: const auto nl = U->map->n;
1797: auto ait = thrust::make_constant_iterator(static_cast<PetscScalar>(atol));
1798: auto rit = thrust::make_constant_iterator(static_cast<PetscScalar>(rtol));
1799: PetscDeviceContext dctx;
1800: cupmStream_t stream;
1802: PetscFunctionBegin;
1803: PetscCall(GetHandles_(&dctx, &stream));
1804: {
1805: const auto ConditionalDeviceArrayRead = [&](Vec v) {
1806: if (v) {
1807: return thrust::device_pointer_cast(DeviceArrayRead(dctx, v).data());
1808: } else {
1809: return thrust::device_ptr<PetscScalar>{nullptr};
1810: }
1811: };
1813: const auto uarr = DeviceArrayRead(dctx, U);
1814: const auto yarr = DeviceArrayRead(dctx, Y);
1815: const auto uptr = thrust::device_pointer_cast(uarr.data());
1816: const auto yptr = thrust::device_pointer_cast(yarr.data());
1817: const auto eptr = ConditionalDeviceArrayRead(E);
1818: const auto rptr = ConditionalDeviceArrayRead(vrtol);
1819: const auto aptr = ConditionalDeviceArrayRead(vatol);
1821: if (!vatol && !vrtol) {
1822: if (E) {
1823: // clang-format off
1824: PetscCall(
1825: detail::ExecuteWNorm<detail::ErrorWNormETransform>(
1826: thrust::make_tuple(uptr, yptr, eptr, ait, rit),
1827: thrust::make_tuple(uptr + nl, yptr + nl, eptr + nl, ait, rit),
1828: wnormtype, stream, ignore_max, norm, norm_loc, norma, norma_loc, normr, normr_loc
1829: )
1830: );
1831: // clang-format on
1832: } else {
1833: // clang-format off
1834: PetscCall(
1835: detail::ExecuteWNorm<detail::ErrorWNormTransform>(
1836: thrust::make_tuple(uptr, yptr, ait, rit),
1837: thrust::make_tuple(uptr + nl, yptr + nl, ait, rit),
1838: wnormtype, stream, ignore_max, norm, norm_loc, norma, norma_loc, normr, normr_loc
1839: )
1840: );
1841: // clang-format on
1842: }
1843: } else if (!vatol) {
1844: if (E) {
1845: // clang-format off
1846: PetscCall(
1847: detail::ExecuteWNorm<detail::ErrorWNormETransform>(
1848: thrust::make_tuple(uptr, yptr, eptr, ait, rptr),
1849: thrust::make_tuple(uptr + nl, yptr + nl, eptr + nl, ait, rptr + nl),
1850: wnormtype, stream, ignore_max, norm, norm_loc, norma, norma_loc, normr, normr_loc
1851: )
1852: );
1853: // clang-format on
1854: } else {
1855: // clang-format off
1856: PetscCall(
1857: detail::ExecuteWNorm<detail::ErrorWNormTransform>(
1858: thrust::make_tuple(uptr, yptr, ait, rptr),
1859: thrust::make_tuple(uptr + nl, yptr + nl, ait, rptr + nl),
1860: wnormtype, stream, ignore_max, norm, norm_loc, norma, norma_loc, normr, normr_loc
1861: )
1862: );
1863: // clang-format on
1864: }
1865: } else if (!vrtol) {
1866: if (E) {
1867: // clang-format off
1868: PetscCall(
1869: detail::ExecuteWNorm<detail::ErrorWNormETransform>(
1870: thrust::make_tuple(uptr, yptr, eptr, aptr, rit),
1871: thrust::make_tuple(uptr + nl, yptr + nl, eptr + nl, aptr + nl, rit),
1872: wnormtype, stream, ignore_max, norm, norm_loc, norma, norma_loc, normr, normr_loc
1873: )
1874: );
1875: // clang-format on
1876: } else {
1877: // clang-format off
1878: PetscCall(
1879: detail::ExecuteWNorm<detail::ErrorWNormTransform>(
1880: thrust::make_tuple(uptr, yptr, aptr, rit),
1881: thrust::make_tuple(uptr + nl, yptr + nl, aptr + nl, rit),
1882: wnormtype, stream, ignore_max, norm, norm_loc, norma, norma_loc, normr, normr_loc
1883: )
1884: );
1885: // clang-format on
1886: }
1887: } else {
1888: if (E) {
1889: // clang-format off
1890: PetscCall(
1891: detail::ExecuteWNorm<detail::ErrorWNormETransform>(
1892: thrust::make_tuple(uptr, yptr, eptr, aptr, rptr),
1893: thrust::make_tuple(uptr + nl, yptr + nl, eptr + nl, aptr + nl, rptr + nl),
1894: wnormtype, stream, ignore_max, norm, norm_loc, norma, norma_loc, normr, normr_loc
1895: )
1896: );
1897: // clang-format on
1898: } else {
1899: // clang-format off
1900: PetscCall(
1901: detail::ExecuteWNorm<detail::ErrorWNormTransform>(
1902: thrust::make_tuple(uptr, yptr, aptr, rptr),
1903: thrust::make_tuple(uptr + nl, yptr + nl, aptr + nl, rptr + nl),
1904: wnormtype, stream, ignore_max, norm, norm_loc, norma, norma_loc, normr, normr_loc
1905: )
1906: );
1907: // clang-format on
1908: }
1909: }
1910: }
1911: PetscFunctionReturn(PETSC_SUCCESS);
1912: }
1914: namespace detail
1915: {
1916: struct dotnorm2_mult {
1917: PETSC_NODISCARD PETSC_HOSTDEVICE_INLINE_DECL thrust::tuple<PetscScalar, PetscScalar> operator()(const PetscScalar &s, const PetscScalar &t) const noexcept
1918: {
1919: const auto conjt = PetscConj(t);
1921: return {s * conjt, t * conjt};
1922: }
1923: };
1925: // it is positively __bananas__ that thrust does not define default operator+ for tuples... I
1926: // would do it myself but now I am worried that they do so on purpose...
1927: struct dotnorm2_tuple_plus {
1928: using value_type = thrust::tuple<PetscScalar, PetscScalar>;
1930: PETSC_NODISCARD PETSC_HOSTDEVICE_INLINE_DECL value_type operator()(const value_type &lhs, const value_type &rhs) const noexcept { return {thrust::get<0>(lhs) + thrust::get<0>(rhs), thrust::get<1>(lhs) + thrust::get<1>(rhs)}; }
1931: };
1933: } // namespace detail
1935: // v->ops->dotnorm2
1936: template <device::cupm::DeviceType T>
1937: inline PetscErrorCode VecSeq_CUPM<T>::DotNorm2(Vec s, Vec t, PetscScalar *dp, PetscScalar *nm) noexcept
1938: {
1939: PetscDeviceContext dctx;
1940: cupmStream_t stream;
1942: PetscFunctionBegin;
1943: PetscCall(GetHandles_(&dctx, &stream));
1944: {
1945: PetscScalar dpt = 0.0, nmt = 0.0;
1946: const auto sdptr = thrust::device_pointer_cast(DeviceArrayRead(dctx, s).data());
1948: // clang-format off
1949: PetscCallThrust(
1950: thrust::tie(*dp, *nm) = THRUST_CALL(
1951: thrust::inner_product,
1952: stream,
1953: sdptr, sdptr+s->map->n, thrust::device_pointer_cast(DeviceArrayRead(dctx, t).data()),
1954: thrust::make_tuple(dpt, nmt),
1955: detail::dotnorm2_tuple_plus{}, detail::dotnorm2_mult{}
1956: );
1957: );
1958: // clang-format on
1959: }
1960: PetscFunctionReturn(PETSC_SUCCESS);
1961: }
1963: namespace detail
1964: {
1965: struct conjugate {
1966: PETSC_NODISCARD PETSC_HOSTDEVICE_INLINE_DECL PetscScalar operator()(const PetscScalar &x) const noexcept { return PetscConj(x); }
1967: };
1969: } // namespace detail
1971: // v->ops->conjugate
1972: template <device::cupm::DeviceType T>
1973: inline PetscErrorCode VecSeq_CUPM<T>::ConjugateAsync(Vec xin, PetscDeviceContext dctx) noexcept
1974: {
1975: PetscFunctionBegin;
1976: if (PetscDefined(USE_COMPLEX)) PetscCall(PointwiseUnary_(detail::conjugate{}, xin, nullptr, dctx));
1977: PetscFunctionReturn(PETSC_SUCCESS);
1978: }
1980: // v->ops->conjugate
1981: template <device::cupm::DeviceType T>
1982: inline PetscErrorCode VecSeq_CUPM<T>::Conjugate(Vec xin) noexcept
1983: {
1984: PetscFunctionBegin;
1985: PetscCall(ConjugateAsync(xin, nullptr));
1986: PetscFunctionReturn(PETSC_SUCCESS);
1987: }
1989: namespace detail
1990: {
1992: struct real_part {
1993: PETSC_NODISCARD PETSC_HOSTDEVICE_INLINE_DECL thrust::tuple<PetscReal, PetscInt> operator()(const thrust::tuple<PetscScalar, PetscInt> &x) const noexcept { return {PetscRealPart(thrust::get<0>(x)), thrust::get<1>(x)}; }
1995: PETSC_NODISCARD PETSC_HOSTDEVICE_INLINE_DECL PetscReal operator()(const PetscScalar &x) const noexcept { return PetscRealPart(x); }
1996: };
1998: // deriving from Operator allows us to "store" an instance of the operator in the class but
1999: // also take advantage of empty base class optimization if the operator is stateless
2000: template <typename Operator>
2001: class tuple_compare : Operator {
2002: public:
2003: using tuple_type = thrust::tuple<PetscReal, PetscInt>;
2004: using operator_type = Operator;
2006: PETSC_NODISCARD PETSC_HOSTDEVICE_INLINE_DECL tuple_type operator()(const tuple_type &x, const tuple_type &y) const noexcept
2007: {
2008: if (op_()(thrust::get<0>(y), thrust::get<0>(x))) {
2009: // if y is strictly greater/less than x, return y
2010: return y;
2011: } else if (thrust::get<0>(y) == thrust::get<0>(x)) {
2012: // if equal, prefer lower index
2013: return thrust::get<1>(y) < thrust::get<1>(x) ? y : x;
2014: }
2015: // otherwise return x
2016: return x;
2017: }
2019: private:
2020: PETSC_NODISCARD PETSC_HOSTDEVICE_INLINE_DECL const operator_type &op_() const noexcept { return *this; }
2021: };
2023: } // namespace detail
2025: template <device::cupm::DeviceType T>
2026: template <typename TupleFuncT, typename UnaryFuncT>
2027: inline PetscErrorCode VecSeq_CUPM<T>::MinMax_(TupleFuncT &&tuple_ftr, UnaryFuncT &&unary_ftr, Vec v, PetscInt *p, PetscReal *m) noexcept
2028: {
2029: PetscFunctionBegin;
2030: PetscCheckTypeNames(v, VECSEQCUPM(), VECMPICUPM());
2031: if (p) *p = -1;
2032: if (const auto n = v->map->n) {
2033: PetscDeviceContext dctx;
2034: cupmStream_t stream;
2036: PetscCall(GetHandles_(&dctx, &stream));
2037: // needed to:
2038: // 1. switch between transform_reduce and reduce
2039: // 2. strip the real_part functor from the arguments
2040: #if PetscDefined(USE_COMPLEX)
2041: #define THRUST_MINMAX_REDUCE(...) THRUST_CALL(thrust::transform_reduce, __VA_ARGS__)
2042: #else
2043: #define THRUST_MINMAX_REDUCE(s, b, e, real_part__, ...) THRUST_CALL(thrust::reduce, s, b, e, __VA_ARGS__)
2044: #endif
2045: {
2046: const auto vptr = thrust::device_pointer_cast(DeviceArrayRead(dctx, v).data());
2048: if (p) {
2049: // clang-format off
2050: const auto zip = thrust::make_zip_iterator(
2051: thrust::make_tuple(std::move(vptr), thrust::make_counting_iterator(PetscInt{0}))
2052: );
2053: // clang-format on
2054: // need to use preprocessor conditionals since otherwise thrust complains about not being
2055: // able to convert a thrust::device_reference<PetscScalar> to a PetscReal on complex
2056: // builds...
2057: // clang-format off
2058: PetscCallThrust(
2059: thrust::tie(*m, *p) = THRUST_MINMAX_REDUCE(
2060: stream, zip, zip + n, detail::real_part{},
2061: thrust::make_tuple(*m, *p), std::forward<TupleFuncT>(tuple_ftr)
2062: );
2063: );
2064: // clang-format on
2065: } else {
2066: // clang-format off
2067: PetscCallThrust(
2068: *m = THRUST_MINMAX_REDUCE(
2069: stream, vptr, vptr + n, detail::real_part{},
2070: *m, std::forward<UnaryFuncT>(unary_ftr)
2071: );
2072: );
2073: // clang-format on
2074: }
2075: }
2076: #undef THRUST_MINMAX_REDUCE
2077: }
2078: // REVIEW ME: flops?
2079: PetscFunctionReturn(PETSC_SUCCESS);
2080: }
2082: // v->ops->max
2083: template <device::cupm::DeviceType T>
2084: inline PetscErrorCode VecSeq_CUPM<T>::Max(Vec v, PetscInt *p, PetscReal *m) noexcept
2085: {
2086: using tuple_functor = detail::tuple_compare<thrust::greater<PetscReal>>;
2087: using unary_functor = thrust::maximum<PetscReal>;
2089: PetscFunctionBegin;
2090: *m = PETSC_MIN_REAL;
2091: // use {} constructor syntax otherwise most vexing parse
2092: PetscCall(MinMax_(tuple_functor{}, unary_functor{}, v, p, m));
2093: PetscFunctionReturn(PETSC_SUCCESS);
2094: }
2096: // v->ops->min
2097: template <device::cupm::DeviceType T>
2098: inline PetscErrorCode VecSeq_CUPM<T>::Min(Vec v, PetscInt *p, PetscReal *m) noexcept
2099: {
2100: using tuple_functor = detail::tuple_compare<thrust::less<PetscReal>>;
2101: using unary_functor = thrust::minimum<PetscReal>;
2103: PetscFunctionBegin;
2104: *m = PETSC_MAX_REAL;
2105: // use {} constructor syntax otherwise most vexing parse
2106: PetscCall(MinMax_(tuple_functor{}, unary_functor{}, v, p, m));
2107: PetscFunctionReturn(PETSC_SUCCESS);
2108: }
2110: // v->ops->sum
2111: template <device::cupm::DeviceType T>
2112: inline PetscErrorCode VecSeq_CUPM<T>::Sum(Vec v, PetscScalar *sum) noexcept
2113: {
2114: PetscFunctionBegin;
2115: if (const auto n = v->map->n) {
2116: PetscDeviceContext dctx;
2117: cupmStream_t stream;
2119: PetscCall(GetHandles_(&dctx, &stream));
2120: const auto dptr = thrust::device_pointer_cast(DeviceArrayRead(dctx, v).data());
2121: // REVIEW ME: why not cupmBlasXasum()?
2122: PetscCallThrust(*sum = THRUST_CALL(thrust::reduce, stream, dptr, dptr + n, PetscScalar{0.0}););
2123: // REVIEW ME: must be at least n additions
2124: PetscCall(PetscLogGpuFlops(n));
2125: } else {
2126: *sum = 0.0;
2127: }
2128: PetscFunctionReturn(PETSC_SUCCESS);
2129: }
2131: template <device::cupm::DeviceType T>
2132: inline PetscErrorCode VecSeq_CUPM<T>::ShiftAsync(Vec v, PetscScalar shift, PetscDeviceContext dctx) noexcept
2133: {
2134: PetscFunctionBegin;
2135: PetscCall(PointwiseUnary_(device::cupm::functors::make_plus_equals(shift), v, nullptr, dctx));
2136: PetscFunctionReturn(PETSC_SUCCESS);
2137: }
2139: template <device::cupm::DeviceType T>
2140: inline PetscErrorCode VecSeq_CUPM<T>::Shift(Vec v, PetscScalar shift) noexcept
2141: {
2142: PetscFunctionBegin;
2143: PetscCall(ShiftAsync(v, shift, nullptr));
2144: PetscFunctionReturn(PETSC_SUCCESS);
2145: }
2147: template <device::cupm::DeviceType T>
2148: inline PetscErrorCode VecSeq_CUPM<T>::SetRandom(Vec v, PetscRandom rand) noexcept
2149: {
2150: PetscFunctionBegin;
2151: if (const auto n = v->map->n) {
2152: PetscBool iscurand;
2153: PetscDeviceContext dctx;
2155: PetscCall(GetHandles_(&dctx));
2156: PetscCall(PetscObjectTypeCompare(PetscObjectCast(rand), PETSCCURAND, &iscurand));
2157: if (iscurand) PetscCall(PetscRandomGetValues(rand, n, DeviceArrayWrite(dctx, v)));
2158: else PetscCall(PetscRandomGetValues(rand, n, HostArrayWrite(dctx, v)));
2159: } else {
2160: PetscCall(MaybeIncrementEmptyLocalVec(v));
2161: }
2162: // REVIEW ME: flops????
2163: // REVIEW ME: Timing???
2164: PetscFunctionReturn(PETSC_SUCCESS);
2165: }
2167: // v->ops->setpreallocation
2168: template <device::cupm::DeviceType T>
2169: inline PetscErrorCode VecSeq_CUPM<T>::SetPreallocationCOO(Vec v, PetscCount ncoo, const PetscInt coo_i[]) noexcept
2170: {
2171: PetscDeviceContext dctx;
2173: PetscFunctionBegin;
2174: PetscCall(GetHandles_(&dctx));
2175: PetscCall(VecSetPreallocationCOO_Seq(v, ncoo, coo_i));
2176: PetscCall(SetPreallocationCOO_CUPMBase(v, ncoo, coo_i, dctx));
2177: PetscFunctionReturn(PETSC_SUCCESS);
2178: }
2180: // v->ops->setvaluescoo
2181: template <device::cupm::DeviceType T>
2182: inline PetscErrorCode VecSeq_CUPM<T>::SetValuesCOO(Vec x, const PetscScalar v[], InsertMode imode) noexcept
2183: {
2184: auto vv = const_cast<PetscScalar *>(v);
2185: PetscMemType memtype;
2186: PetscDeviceContext dctx;
2187: cupmStream_t stream;
2189: PetscFunctionBegin;
2190: PetscCall(GetHandles_(&dctx, &stream));
2191: PetscCall(PetscGetMemType(v, &memtype));
2192: if (PetscMemTypeHost(memtype)) {
2193: const auto size = VecIMPLCast(x)->coo_n;
2195: // If user gave v[] in host, we might need to copy it to device if any
2196: PetscCall(PetscDeviceMalloc(dctx, PETSC_MEMTYPE_CUPM(), size, &vv));
2197: PetscCall(PetscCUPMMemcpyAsync(vv, v, size, cupmMemcpyHostToDevice, stream));
2198: }
2200: if (const auto n = x->map->n) {
2201: const auto vcu = VecCUPMCast(x);
2203: PetscCall(PetscCUPMLaunchKernel1D(n, 0, stream, kernels::add_coo_values, vv, n, vcu->jmap1_d, vcu->perm1_d, imode, imode == INSERT_VALUES ? DeviceArrayWrite(dctx, x).data() : DeviceArrayReadWrite(dctx, x).data()));
2204: } else {
2205: PetscCall(MaybeIncrementEmptyLocalVec(x));
2206: }
2208: if (PetscMemTypeHost(memtype)) PetscCall(PetscDeviceFree(dctx, vv));
2209: PetscCall(PetscDeviceContextSynchronize(dctx));
2210: PetscFunctionReturn(PETSC_SUCCESS);
2211: }
2213: } // namespace impl
2215: } // namespace cupm
2217: } // namespace vec
2219: } // namespace Petsc