1// FEAT3: Finite Element Analysis Toolbox, Version 3
2// Copyright (C) 2010 by Stefan Turek & the FEAT group
3// FEAT3 is released under the GNU General Public License version 3,
4// see the file 'copyright.txt' in the top level directory for details.
5#include <kernel/base_header.hpp>
6#include <kernel/lafem/arch/batched_kernel_helper.cuh>
7#include <kernel/lafem/arch/batched_vector_apply.hpp>
8#include <kernel/util/cuda_util.hpp>
9#include <kernel/util/memory_aux.hpp>
10#include <kernel/util/memory_arbiter.hpp>
12#include <cooperative_groups.h>
16#include <kernel/util/cuda_helper.cuh>
18namespace FEAT::LAFEM::Arch
20 namespace cg = cooperative_groups;
24 // Persistent, lazily-grown device scratch reused across the batched-kernel calls, so that the
25 // per-call cudaMalloc/cudaFree (each of which synchronizes the device) is avoided. There are two
26 // arenas: one for the value scratch (device_dots / device_scales) and one for the device pointer
27 // table (other_ptrs). Reuse is safe because all batched ops are issued serially on the default
28 // stream, so a buffer is only overwritten after the prior kernel that read it has completed
29 // (stream ordering); the host orchestration is single-threaded. The buffers grow monotonically and
30 // are released at CUDA teardown by the runtime; they are only used by the GMRES driver, not by the
31 // leak-checked kernel unit tests.
32 void* g_scratch_val = nullptr;
33 size_t g_scratch_val_bytes = 0u;
34 void* g_scratch_ptr = nullptr;
35 size_t g_scratch_ptr_bytes = 0u;
37 void* grow_scratch(void*& buf, size_t& cap, size_t bytes)
41 // Register the teardown hook the first time we allocate any scratch. This decouples the
42 // low-level util layer (which owns cuda_finalize) from this module: util does not depend on
43 // LAFEM, and if the batched kernels are never used, nothing is registered and nothing is
44 // freed. Registration is safe to do here because the batched ops are issued single-threaded.
45 static bool finalize_registered = false;
46 if(!finalize_registered)
48 Util::cuda_register_finalize_callback(&BatchedScratchSpace::free);
49 finalize_registered = true;
53 Memory::free_cuda(buf);
54 size_t new_bytes = 2u*bytes;
55 buf = Memory::alloc_cuda(new_bytes);
61 void free_scratch_space()
65 Memory::free_cuda(g_scratch_val);
66 g_scratch_val_bytes = 0u;
70 Memory::free_cuda(g_scratch_ptr);
71 g_scratch_ptr_bytes = 0u;
76 void BatchedScratchSpace::free()
83 template<typename DT_, typename DTT_>
84 void BatchedDotProduct::exec_cuda(Memory::Arbiter& local_dots, const Memory::Arbiter& target, Index dot_size, Memory::Arbiter const * const * others, Index num_dots)
86 constexpr Index max_size_ = 1024u;
87 constexpr Index blocksize = 256u;
88 // constexpr Index blocksize = 32u;
89 constexpr int num_batch = 4;
90 // constexpr int num_batch = 16;
92 std::array<Memory::TypedView<DTT_>, max_size_> static_views;
93 std::array<DTT_ const*, max_size_> static_p;
97 block.x = (unsigned)blocksize;
99 // x grid dimension resoluts dot_size, modulo we want to load multiple values per
100 // TODO: change with int variants
101 grid.x = (unsigned)ceil((dot_size)/(double)(block.x*2*10));
102 // grid.x = (unsigned)1;
103 grid.y = (unsigned)ceil((num_dots)/(double)(block.y));
105 // the cuda kernel operates on device memory, so it acquires cuda read views itself
106 Memory::TypedView<DTT_> target_view(target.view(Memory::Location::cuda, Memory::Access::read));
107 const DTT_* target_ptr = target_view.get_r();
108 Memory::TypedView<DTT_>* tmp_views = static_views.data();
109 const DTT_ ** tmp_p = static_p.data();
110 if(num_dots > max_size_)
112 using HType = const DTT_*;
113 tmp_views = new Memory::TypedView<DTT_>[num_dots];
114 tmp_p = new HType[num_dots];
116 for(Index l = 0; l < num_dots; ++l)
118 tmp_views[l] = Memory::TypedView<DTT_>(others[l]->view(Memory::Location::cuda, Memory::Access::read));
119 tmp_p[l] = tmp_views[l].get_r();
122 // device pointer table for the "others" (transient device scratch)
123 DTT_ const ** other_ptrs = static_cast<DTT_ const**>(grow_scratch(g_scratch_ptr, g_scratch_ptr_bytes, num_dots*sizeof(DTT_*)));
124 cudaCheck(cudaMemcpyAsync(other_ptrs, tmp_p, num_dots * sizeof(DTT_*), cudaMemcpyHostToDevice), "cudaMemcpyAsync");
126 if constexpr(std::is_same_v<DT_, DTT_>)
128 Memory::TypedView<DT_> dots_view(local_dots.view(Memory::Location::cuda, Memory::Access::read_write));
129 DT_* device_dots = dots_view.get_w();
130 cuda_batched_dot<DTT_, blocksize><<<grid, block, blocksize*num_batch*sizeof(DTT_)>>>(device_dots, target_ptr, dot_size, other_ptrs, num_dots);
134 // mixed precision: accumulate in the compute type DTT_ on a scratch buffer, then convert-add into
135 // the DT_ result arbiter on the host
136 DTT_* device_dots = static_cast<DTT_*>(grow_scratch(g_scratch_val, g_scratch_val_bytes, num_dots*sizeof(DTT_)));
137 Memory::format_cuda(device_dots, DTT_(0), num_dots);
138 cuda_batched_dot<DTT_, blocksize><<<grid, block, blocksize*num_batch*sizeof(DTT_)>>>(device_dots, target_ptr, dot_size, other_ptrs, num_dots);
139 DTT_* tmp = static_cast<DTT_*>(Memory::alloc_main(sizeof(DTT_)*num_dots));
140 Memory::memcopy_cuda_to_main(tmp, device_dots, num_dots * sizeof(DTT_));
141 Memory::TypedView<DT_> dots_view(local_dots.view(Memory::Location::main, Memory::Access::read_write));
142 DT_* dots_ptr = dots_view.get_w();
143 for(Index l = 0; l < num_dots; ++l)
145 dots_ptr[l] += DT_(tmp[l]);
147 Memory::free_main(tmp);
149 if(num_dots > max_size_)
155 #ifdef FEAT_DEBUG_MODE
156 Util::cuda_synchronize();
157 cudaError_t last_error(cudaGetLastError());
158 if (cudaSuccess != last_error)
159 throw InternalError(__func__, __FILE__, __LINE__, "CUDA error occurred in execution!\n" + stringify(cudaGetErrorString(last_error)));
164 template<typename DT_, typename DTT_>
165 void BatchedTripleDotProduct::exec_cuda(Memory::Arbiter& local_dots, const Memory::Arbiter& target, Index dot_size, Memory::Arbiter const * const * others, const Memory::Arbiter& freqs, Index num_dots)
167 constexpr Index max_size_ = 1024u;
168 constexpr Index blocksize = 256u;
169 // constexpr Index blocksize = 32u;
170 constexpr int num_batch = 4;
171 // constexpr int num_batch = 16;
173 std::array<Memory::TypedView<DTT_>, max_size_> static_views;
174 std::array<DTT_ const*, max_size_> static_p;
180 block.x = (unsigned)blocksize;
182 // x grid dimension resoluts dot_size, modulo we want to load multiple values per
183 grid.x = (unsigned)ceil((dot_size)/(double)(block.x*2*10));
184 // grid.x = (unsigned)1;
185 grid.y = (unsigned)ceil((num_dots)/(double)(block.y));
187 // the cuda kernel operates on device memory, so it acquires cuda read views itself
188 Memory::TypedView<DTT_> target_view(target.view(Memory::Location::cuda, Memory::Access::read));
189 const DTT_* target_ptr = target_view.get_r();
190 Memory::TypedView<DTT_> freqs_view(freqs.view(Memory::Location::cuda, Memory::Access::read));
191 const DTT_* freqs_ptr = freqs_view.get_r();
192 Memory::TypedView<DTT_>* tmp_views = static_views.data();
193 const DTT_ ** tmp_p = static_p.data();
194 if(num_dots > max_size_)
196 using HType = const DTT_*;
197 tmp_views = new Memory::TypedView<DTT_>[num_dots];
198 tmp_p = new HType[num_dots];
200 for(Index l = 0; l < num_dots; ++l)
202 tmp_views[l] = Memory::TypedView<DTT_>(others[l]->view(Memory::Location::cuda, Memory::Access::read));
203 tmp_p[l] = tmp_views[l].get_r();
206 // device pointer table for the "others" (transient device scratch)
207 DTT_ const ** other_ptrs = static_cast<DTT_ const**>(grow_scratch(g_scratch_ptr, g_scratch_ptr_bytes, num_dots*sizeof(DTT_*)));
208 cudaCheck(cudaMemcpyAsync(other_ptrs, tmp_p, num_dots * sizeof(DTT_*), cudaMemcpyHostToDevice), "cudaMemcpyAsync");
210 if constexpr(std::is_same_v<DT_, DTT_>)
212 // accumulate straight into the caller's result arbiter on the device (see batched_dot_cuda)
213 Memory::TypedView<DT_> dots_view(local_dots.view(Memory::Location::cuda, Memory::Access::read_write));
214 DT_* device_dots = dots_view.get_w();
215 cuda_batched_triple_dot<DTT_, blocksize><<<grid, block, blocksize*num_batch*sizeof(DTT_)>>>(device_dots, target_ptr, dot_size, other_ptrs, freqs_ptr, num_dots);
219 // mixed precision: accumulate in DTT_ on scratch, then convert-add into the DT_ result arbiter
220 DTT_* device_dots = static_cast<DTT_*>(grow_scratch(g_scratch_val, g_scratch_val_bytes, num_dots*sizeof(DTT_)));
221 Memory::format_cuda(device_dots, DTT_(0), num_dots);
222 cuda_batched_triple_dot<DTT_, blocksize><<<grid, block, blocksize*num_batch*sizeof(DTT_)>>>(device_dots, target_ptr, dot_size, other_ptrs, freqs_ptr, num_dots);
223 DTT_* tmp = static_cast<DTT_*>(Memory::alloc_main(sizeof(DTT_)*num_dots));
224 Memory::memcopy_cuda_to_main(tmp, device_dots, num_dots * sizeof(DTT_));
225 Memory::TypedView<DT_> dots_view(local_dots.view(Memory::Location::main, Memory::Access::read_write));
226 DT_* dots_ptr = dots_view.get_w();
227 for(Index l = 0; l < num_dots; ++l)
229 dots_ptr[l] += DT_(tmp[l]);
231 Memory::free_main(tmp);
234 if(num_dots > max_size_)
240 #ifdef FEAT_DEBUG_MODE
241 Util::cuda_synchronize();
242 cudaError_t last_error(cudaGetLastError());
243 if (cudaSuccess != last_error)
244 throw InternalError(__func__, __FILE__, __LINE__, "CUDA error occurred in execution!\n" + stringify(cudaGetErrorString(last_error)));
250 template<typename DT_>
251 void CumulativeAxpy::exec_cuda(Memory::Arbiter& target, Index vec_size, Memory::Arbiter const * const * others, DT_ const * const local_scales, Index num_axpy, DT_ alpha)
253 constexpr Index max_size_ = 1024u;
254 constexpr Index blocksize = 128u;
257 block.x = (unsigned)blocksize;
258 // one block always does a warp size chunk of target (due to load coalescing)
259 grid.x = (unsigned)ceil((vec_size)/(double)((32)));
261 std::array<Memory::TypedView<DT_>, max_size_> static_views;
262 std::array<DT_ const*, max_size_> static_p;
264 // the cuda kernel operates on device memory, so it acquires its cuda views itself
265 Memory::TypedView<DT_> target_view(target.view(Memory::Location::cuda, Memory::Access::read_write));
266 DT_* target_ptr = target_view.get_w();
268 Memory::TypedView<DT_>* tmp_views = static_views.data();
269 const DT_ ** tmp_p = static_p.data();
270 if(num_axpy > max_size_)
272 using HType = const DT_*;
273 tmp_views = new Memory::TypedView<DT_>[num_axpy];
274 tmp_p = new HType[num_axpy];
276 for(Index l = 0; l < num_axpy; ++l)
278 tmp_views[l] = Memory::TypedView<DT_>(others[l]->view(Memory::Location::cuda, Memory::Access::read));
279 tmp_p[l] = tmp_views[l].get_r();
283 // reuse the persistent scratch arenas instead of allocating/freeing per call
284 DT_* device_scales = static_cast<DT_*>(grow_scratch(g_scratch_val, g_scratch_val_bytes, num_axpy*sizeof(DT_)));
285 DT_ const ** other_ptrs = static_cast<DT_ const**>(grow_scratch(g_scratch_ptr, g_scratch_ptr_bytes, num_axpy*sizeof(DT_*)));
286 // stream ordered calls, so no explicit sync required
287 cudaCheck(cudaMemcpyAsync(other_ptrs, tmp_p, num_axpy * sizeof(DT_*), cudaMemcpyHostToDevice), "cudaMemcpyAsync");
289 cudaCheck(cudaMemcpyAsync(device_scales, local_scales, num_axpy * sizeof(DT_), cudaMemcpyHostToDevice), "cudaMemcpyAsync");
291 cuda_cumulative_axpy<DT_, blocksize><<<grid, block, blocksize*sizeof(DT_)>>>(target_ptr, vec_size, other_ptrs, device_scales, num_axpy, DT_(alpha));
293 // release and destroy the in-place constructed views (see the placement-new above)
294 if(num_axpy > max_size_)
300 #ifdef FEAT_DEBUG_MODE
301 Util::cuda_synchronize();
302 cudaError_t last_error(cudaGetLastError());
303 if (cudaSuccess != last_error)
304 throw InternalError(__func__, __FILE__, __LINE__, "CUDA error occurred in execution!\n" + stringify(cudaGetErrorString(last_error)));
312template void FEAT::LAFEM::Arch::BatchedDotProduct::exec_cuda<double, double>(FEAT::Memory::Arbiter&, const FEAT::Memory::Arbiter&, FEAT::Index, FEAT::Memory::Arbiter const * const *, FEAT::Index);
313template void FEAT::LAFEM::Arch::BatchedDotProduct::exec_cuda<double, float>(FEAT::Memory::Arbiter&, const FEAT::Memory::Arbiter&, FEAT::Index, FEAT::Memory::Arbiter const * const *, FEAT::Index);
314template void FEAT::LAFEM::Arch::BatchedDotProduct::exec_cuda<float, double>(FEAT::Memory::Arbiter&, const FEAT::Memory::Arbiter&, FEAT::Index, FEAT::Memory::Arbiter const * const *, FEAT::Index);
315template void FEAT::LAFEM::Arch::BatchedDotProduct::exec_cuda<float, float>(FEAT::Memory::Arbiter&, const FEAT::Memory::Arbiter&, FEAT::Index, FEAT::Memory::Arbiter const * const *, FEAT::Index);
317template void FEAT::LAFEM::Arch::BatchedTripleDotProduct::exec_cuda<double, double>(FEAT::Memory::Arbiter&, const FEAT::Memory::Arbiter&, FEAT::Index, FEAT::Memory::Arbiter const * const *, const FEAT::Memory::Arbiter&, FEAT::Index);
318template void FEAT::LAFEM::Arch::BatchedTripleDotProduct::exec_cuda<double, float>(FEAT::Memory::Arbiter&, const FEAT::Memory::Arbiter&, FEAT::Index, FEAT::Memory::Arbiter const * const *, const FEAT::Memory::Arbiter&, FEAT::Index);
319template void FEAT::LAFEM::Arch::BatchedTripleDotProduct::exec_cuda<float, double>(FEAT::Memory::Arbiter&, const FEAT::Memory::Arbiter&, FEAT::Index, FEAT::Memory::Arbiter const * const *, const FEAT::Memory::Arbiter&, FEAT::Index);
320template void FEAT::LAFEM::Arch::BatchedTripleDotProduct::exec_cuda<float, float>(FEAT::Memory::Arbiter&, const FEAT::Memory::Arbiter&, FEAT::Index, FEAT::Memory::Arbiter const * const *, const FEAT::Memory::Arbiter&, FEAT::Index);
322template void FEAT::LAFEM::Arch::CumulativeAxpy::exec_cuda<double>(FEAT::Memory::Arbiter&, FEAT::Index, FEAT::Memory::Arbiter const * const *, double const *const, FEAT::Index, double);
323template void FEAT::LAFEM::Arch::CumulativeAxpy::exec_cuda<float>(FEAT::Memory::Arbiter&, FEAT::Index, FEAT::Memory::Arbiter const * const *, float const *const, FEAT::Index, float);