Nektar++
Loading...
Searching...
No Matches
LoopExecutionHIPCUDA.hpp
Go to the documentation of this file.
1///////////////////////////////////////////////////////////////////////////////
2//
3// File: LoopExecutionHIPCUDA.hpp
4//
5// For more information, please see: http://www.nektar.info
6//
7// The MIT License
8//
9// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
10// Department of Aeronautics, Imperial College London (UK), and Scientific
11// Computing and Imaging Institute, University of Utah (USA).
12//
13// Permission is hereby granted, free of charge, to any person obtaining a
14// copy of this software and associated documentation files (the "Software"),
15// to deal in the Software without restriction, including without limitation
16// the rights to use, copy, modify, merge, publish, distribute, sublicense,
17// and/or sell copies of the Software, and to permit persons to whom the
18// Software is furnished to do so, subject to the following conditions:
19//
20// The above copyright notice and this permission notice shall be included
21// in all copies or substantial portions of the Software.
22//
23// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
24// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
26// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
28// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
29// DEALINGS IN THE SOFTWARE.
30//
31// Description:
32//
33///////////////////////////////////////////////////////////////////////////////
34
35#pragma once
36
37#if (defined(NEKTAR_ENABLE_CUDA) && defined(DEVICE_COMPILE_ONLY)) || \
38 (defined(NEKTAR_ENABLE_HIP) && defined(DEVICE_COMPILE_ONLY))
39
40#include <float.h>
41
42namespace Nektar
43{
44
45// Parallel for kernel.
46template <typename Functor,
47 unsigned int blockSize = NektarSpaces::Device::defaultBlockSize>
48__global__ __launch_bounds__(blockSize) void parallel_for(const size_t begin,
49 const size_t end,
50 const Functor functor)
51{
52 size_t i = begin + blockDim.x * blockIdx.x + threadIdx.x;
53
54 while (i < end)
55 {
56 functor(i);
57 i += blockDim.x * gridDim.x;
58 }
59}
60
61// Parallel for launchers.
62template <
63 typename ExecSpace, typename Functor,
64 std::enable_if_t<std::is_same_v<ExecSpace, NektarSpaces::Device>, bool>
65 Enable = true>
66inline void parallel_for(const size_t begin, const size_t end,
67 const Functor &functor)
68{
69 // CUDA/HIP kernel launches require every grid dimension to be >= 1;
70 // launching with gridDim.x == 0 (which naturally happens here whenever
71 // the loop range is empty, e.g. end == begin) is rejected by the
72 // runtime with an "invalid argument" error rather than silently doing
73 // nothing. There is trivially no work to do in that case, so skip the
74 // launch entirely instead.
75 if (end <= begin)
76 {
77 return;
78 }
79
80 const unsigned int streamID = internalLoopExecutionStreamID;
81 const unsigned int blockSize = NektarSpaces::Device::defaultBlockSize;
82 const unsigned int gridSize = ((end - begin) + blockSize - 1u) / blockSize;
83
84#if defined(NEKTAR_ENABLE_CUDA)
85 auto stream = CUDAStream::GetInstance(streamID);
86#elif defined(NEKTAR_ENABLE_HIP)
87 auto stream = HIPStream::GetInstance(streamID);
88#endif
89
90 parallel_for<<<gridSize, blockSize, 0, stream>>>(begin, end, functor);
92}
93
94// Sets *dest to val if init, and otherwise combines val into it by Reduction.
95// Set, it has a single writer. Combined into, it may be shared with the
96// reductions of other blocks of a Field on other streams, so takes one
97// global-scope atomic.
98template <bool init, typename Reduction>
99NEK_DEVICE_INLINE static void reduce_store(
100 typename Reduction::value_type *const dest,
101 const typename Reduction::value_type val)
102{
103 using TData = typename Reduction::value_type;
104 if constexpr (init)
105 {
106 *dest = val;
107 }
108 else if constexpr (std::is_same_v<Reduction, Nektar::ReduceSum<TData>>)
109 {
110 atomic_add<NektarSpaces::GlobalScope>(dest, val);
111 }
112 else if constexpr (std::is_same_v<Reduction, Nektar::ReduceMax<TData>>)
113 {
114 atomic_max<NektarSpaces::GlobalScope>(dest, val);
115 }
116 else if constexpr (std::is_same_v<Reduction, Nektar::ReduceMin<TData>>)
117 {
118 atomic_min<NektarSpaces::GlobalScope>(dest, val);
119 }
120}
121
122// Partial results of nred values per thread block: functor(i, vals) writes
123// those of index i to vals[0, nred), which Reduction combines. Result s of
124// block b is in buffer[s * gridDim.x + b], which it is set to if init and is
125// otherwise combined into.
126template <bool init, typename Reduction, unsigned int nred, typename Functor,
127 unsigned int blockSize = NektarSpaces::Device::reductionBlockSize()>
128__global__ __launch_bounds__(blockSize) void reduceNKernel(
129 const size_t begin, const size_t end,
130 typename Reduction::value_type *buffer, const Functor functor)
131{
132 using TData = typename Reduction::value_type;
133
134 constexpr TData identity = reduce_identity<Reduction>();
135 constexpr unsigned int warpsize = NektarSpaces::Device::warpSize;
136
137 auto grid = cg::this_grid();
138 auto block = cg::this_thread_block();
139 auto warp = cg::tiled_partition<warpsize>(block);
140 TData v[nred];
141
142 for (unsigned int s = 0; s < nred; ++s)
143 {
144 v[s] = identity;
145 }
146
147 for (size_t tid = begin + grid.thread_rank(); tid < end; tid += grid.size())
148 {
149 TData vals[nred];
150 functor(tid, vals);
151 for (unsigned int s = 0; s < nred; ++s)
152 {
153 v[s] = reduce_join<Reduction>(v[s], vals[s]);
154 }
155 }
156
157 for (unsigned int s = 0; s < nred; ++s)
158 {
159 v[s] = blockReduceWarpPartials(v[s], identity, [&](TData x) {
160#pragma unroll
161 for (unsigned int offset = warpsize / 2; offset > 0; offset /= 2)
162 {
163 x = reduce_join<Reduction>(x, warp.shfl_down(x, offset));
164 }
165 return x;
166 });
167 }
168
169 if (block.thread_rank() == 0)
170 {
171 for (unsigned int s = 0; s < nred; ++s)
172 {
173 reduce_store<init, Reduction>(
174 &buffer[s * gridDim.x + block.group_index().x], v[s]);
175 }
176 }
177}
178
179// Parallel reduction launchers without device-to-host copy.
180template <
181 typename ExecSpace, bool init, typename Reduction, typename Functor,
182 std::enable_if_t<std::is_same_v<ExecSpace, NektarSpaces::Device>, bool>
183 Enable = true>
184inline void parallel_reduce(const size_t begin, const size_t end,
185 const Functor &functor,
186 typename Reduction::value_type *out)
187{
188 using TData = typename Reduction::value_type;
189
190 const unsigned int streamID = internalLoopExecutionStreamID;
191 const unsigned int blockSize = NektarSpaces::Device::reductionBlockSize();
192 const unsigned int gridSize =
194
195#if defined(NEKTAR_ENABLE_CUDA)
196 auto stream = CUDAStream::GetInstance(streamID);
197#elif defined(NEKTAR_ENABLE_HIP)
198 auto stream = HIPStream::GetInstance(streamID);
199#endif
200
201 if (internalMemoryBufferMap.find(streamID) == internalMemoryBufferMap.end())
202 {
203 deviceMalloc(&internalMemoryBufferMap[streamID],
204 internalReductionBufferSize, streamID);
205 }
206
207 TData *buffer = (TData *)internalMemoryBufferMap[streamID];
208 reduceNKernel<true, Reduction, 1><<<gridSize, blockSize, 0, stream>>>(
209 begin, end, buffer,
210 [=] __device__(const size_t i, TData *vals) { vals[0] = functor(i); });
212 reduceNKernel<init, Reduction, 1><<<1, blockSize, 0, stream>>>(
213 0, gridSize, out,
214 [=] __device__(const size_t i, TData *vals) { vals[0] = buffer[i]; });
216}
217
218// Parallel reduction launchers with device-to-host copy.
219template <
220 typename ExecSpace, typename Reduction, typename Functor,
221 std::enable_if_t<std::is_same_v<ExecSpace, NektarSpaces::Device>, bool>
222 Enable = true>
223inline void parallel_reduce(const size_t begin, const size_t end,
224 const Functor &functor,
225 typename Reduction::value_type &out)
226{
227 using TData = typename Reduction::value_type;
228
229 const unsigned int streamID = internalLoopExecutionStreamID;
230 if (internalHostBuffer == nullptr)
231 {
232 hostMallocPinned(&internalHostBuffer, internalMaxDataSizeByte);
233 deviceMalloc(&internalDeviceBuffer, internalMaxDataSizeByte, streamID);
234 }
235
236 parallel_reduce<ExecSpace, true, Reduction>(begin, end, functor,
237 (TData *)internalDeviceBuffer);
238
239 deviceMemcpy<eDeviceToHost>(internalHostBuffer, internalDeviceBuffer,
240 sizeof(TData), streamID);
241
242 out = *(TData *)internalHostBuffer;
243}
244
245// Parallel reduction of nred values without device-to-host copy:
246// functor(i, vals) writes those of index i to vals[0, nred), which Reduction
247// combines into out[0, nred), together with the values already there unless
248// init. At most internalReductionMaxValues values, the partial results the
249// reduction scratch holds.
250template <
251 typename ExecSpace, bool init, typename Reduction, unsigned int nred,
252 typename Functor,
253 std::enable_if_t<std::is_same_v<ExecSpace, NektarSpaces::Device>, bool>
254 Enable = true>
255inline void parallel_reduce(const size_t begin, const size_t end,
256 const Functor &functor,
257 typename Reduction::value_type *out)
258{
259 using TData = typename Reduction::value_type;
260
261 static_assert(nred <= internalReductionMaxValues,
262 "parallel_reduce: too many values.");
263
264 const unsigned int streamID = internalLoopExecutionStreamID;
265 const unsigned int blockSize = NektarSpaces::Device::reductionBlockSize();
266 const unsigned int gridSize =
268
269 ASSERTL0(nred * gridSize * sizeof(TData) <= internalReductionBufferSize,
270 "Too many values for the reduction buffer.");
271
272#if defined(NEKTAR_ENABLE_CUDA)
273 auto stream = CUDAStream::GetInstance(streamID);
274#elif defined(NEKTAR_ENABLE_HIP)
275 auto stream = HIPStream::GetInstance(streamID);
276#endif
277
278 if (internalMemoryBufferMap.find(streamID) == internalMemoryBufferMap.end())
279 {
280 deviceMalloc(&internalMemoryBufferMap[streamID],
281 internalReductionBufferSize, streamID);
282 }
283
284 TData *buffer = (TData *)internalMemoryBufferMap[streamID];
285 reduceNKernel<true, Reduction, nred>
286 <<<gridSize, blockSize, 0, stream>>>(begin, end, buffer, functor);
288 reduceNKernel<init, Reduction, nred><<<1, blockSize, 0, stream>>>(
289 0, gridSize, out, [=] __device__(const size_t i, TData *vals) {
290 for (unsigned int s = 0; s < nred; ++s)
291 {
292 vals[s] = buffer[s * gridSize + i];
293 }
294 });
296}
297
298} // namespace Nektar
299
300#endif
#define NEK_DEVICE_INLINE
Definition Backends.hpp:283
#define CHECK_LAST_HIPCUDA_ERROR()
#define ASSERTL0(condition, msg)
static cudaStream_t & GetInstance(unsigned int id)
static hipStream_t & GetInstance(unsigned int id)
Definition HIPStream.hpp:85
array buffer
Definition GsLib.hpp:81
NEK_DEVICE_KERNEL void const TData *NEK_RESTRICT const TData *NEK_RESTRICT const size_t const unsigned int const unsigned int const unsigned int const unsigned int const size_t const TData *NEK_RESTRICT const TData *NEK_RESTRICT const TUseSharedWsp TData *NEK_RESTRICT const TData *NEK_RESTRICT TData *NEK_RESTRICT out
void parallel_for(const size_t begin, const size_t end, const Functor &functor)
unsigned int internalLoopExecutionStreamID
void deviceMalloc(TData **src, const size_t size, const unsigned int streamID, const MemAllocType memAllocType=eHostPageable)
void parallel_reduce(const size_t begin, const size_t end, const Functor &functor, typename Reduction::value_type *red)
void hostMallocPinned(TData **src, const size_t size)
constexpr unsigned int internalReductionMaxValues
Definition Backends.hpp:67
static constexpr unsigned int defaultBlockSize
Definition Backends.hpp:141
static constexpr unsigned int reductionBlockSize()
Definition Backends.hpp:147
static constexpr unsigned int warpSize
Definition Backends.hpp:143
static constexpr unsigned int reductionGridSize(const size_t n)
Definition Backends.hpp:156