FEAT 3
Finite Element Analysis Toolbox
Loading...
Searching...
No Matches
amavanka_gmres.cu
1#include <kernel/base_header.hpp>
2#include <kernel/util/memory_aux.hpp>
3#include <kernel/util/memory_arbiter.hpp>
4#include <kernel/lafem/vector_mirror.hpp>
5#include <kernel/global/gate.hpp>
6#include <kernel/global/synch_vec.hpp>
7#include <kernel/lafem/arch/batched_vector_apply.hpp>
8#include <kernel/lafem/arch/batched_kernel_helper.cuh>
9#include <kernel/solver/base.hpp>
10#include <kernel/solver/amavanka_gmres.hpp>
11#include <kernel/util/cuda_util.hpp>
12#include <kernel/solver/backend_aux/csr_apply_helper.hpp>
13#include "cusparse_v2.h"
14#include <cublas_v2.h>
15#include <cuda/atomic>
16
17#include <kernel/util/cuda_helper.cuh>
18
19
20namespace FEAT::Solver::VankaGMRES
21{
22
23 namespace cg = cooperative_groups;
24
25 struct CuMatDesc
26 {
27 cusparseSpMatDescr_t descr=0;
28 void* buffer=nullptr;
29 };
30
31
32 namespace Intern
33 {
34 // The matrix value/row/column device pointers are resolved by the caller from the matrix
35 // arbiters (cuda read views, kept alive for the descriptor's lifetime) and passed in here.
36 template<typename DT_, typename IT_>
37 CUDA_HOST void alloc_cusparse_interface(cusparseOperation_t op, cudaDataType_t dt, cudaDataType_t ct, cusparseIndexType_t it,
38 cusparseDnVecDescr_t dx, cusparseDnVecDescr_t dr,
39 const void* row_ptr, const void* col_ptr, const void* val_ptr, Index num_rows, Index num_cols, Index used_elements,
40 CuMatDesc& mat_desc, const DT_& alpha, const DT_& beta)
41 {
42 const auto algo = CUSPARSE_SPMV_CSR_ALG1;
43
44 cusparseStatus_t cu_status = cusparseCreateCsr(&mat_desc.descr, num_rows, num_cols, used_elements, (void*)row_ptr, (void*)col_ptr, (void*)val_ptr,
45 it, it, CUSPARSE_INDEX_BASE_ZERO, dt);
46 if(cu_status != CUSPARSE_STATUS_SUCCESS)
47 throw InternalError(__func__, __FILE__, __LINE__, "cusparseCreateCsr failed with status code: " + stringify(cusparseGetErrorString(cu_status)));
48
49 size_t buffer_size(0);
50 cu_status = cusparseSpMV_bufferSize(Util::Intern::cusparse_handle, op, &alpha, mat_desc.descr, dx, &beta, dr, ct, algo, &buffer_size);
51 if(cu_status != CUSPARSE_STATUS_SUCCESS)
52 throw InternalError(__func__, __FILE__, __LINE__, "cusparseSpMV_bufferSize failed with status code: " + stringify(cusparseGetErrorString(cu_status)));
53
54 mat_desc.buffer = Memory::alloc_cuda(buffer_size);
55 cu_status = cusparseSpMV_preprocess(Util::Intern::cusparse_handle, op, &alpha, mat_desc.descr, dx, &beta, dr, ct, algo, mat_desc.buffer);
56 if(cu_status != CUSPARSE_STATUS_SUCCESS)
57 throw InternalError(__func__, __FILE__, __LINE__, "cusparseSpMV_preprocess failed with status code: " + stringify(cusparseGetErrorString(cu_status)));
58 }
59
60 static void cumat_free(CuMatDesc& mat_desc)
61 {
62 Memory::free_cuda(mat_desc.buffer);
63 mat_desc.buffer = nullptr;
64 cusparseDestroySpMat(mat_desc.descr);
65 mat_desc.descr = 0;
66 }
67
68 template<typename DT_>
69 static void apply_cu_spmv(cusparseOperation_t op, cudaDataType_t ct, cusparseDnVecDescr_t dx, cusparseDnVecDescr_t dr, const CuMatDesc& mat_desc, DT_ alpha, DT_ beta)
70 {
71 cusparseStatus_t status = cusparseSpMV(Util::Intern::cusparse_handle, op, &alpha, mat_desc.descr, dx, &beta, dr, ct, CUSPARSE_SPMV_CSR_ALG1, mat_desc.buffer);
72 if (status != CUSPARSE_STATUS_SUCCESS)
73 throw InternalError(__func__, __FILE__, __LINE__, "cusparseSpMV failed with status code: " + stringify(cusparseGetErrorString(status)));
74 }
75
76 template<typename DT_>
77 static void cublas_dot(DT_& result, const DT_* x, const DT_* y, Index size, cudaDataType_t dt)
78 {
79 cublasStatus_t status;
80 result = DT_(0);
81
82 status = cublasDotEx(Util::Intern::cublas_handle, int(size), x, dt, 1, y, dt, 1, &result, dt, dt);
83 if (status != CUBLAS_STATUS_SUCCESS)
84 throw InternalError(__func__, __FILE__, __LINE__, "cuda error: " + stringify(cublasGetStatusString(status)));
85 }
86
87 template<typename DT_>
88 static void cublas_scale(DT_* x, DT_ a, Index size, cudaDataType_t dt)
89 {
90 cublasStatus_t status = cublasScalEx(Util::Intern::cublas_handle, int(size), &a, dt, x, dt, 1, dt);
91 if (status != CUBLAS_STATUS_SUCCESS)
92 throw InternalError(__func__, __FILE__, __LINE__, "cuda error: " + stringify(cublasGetStatusString(status)));
93 }
94
95 template<typename DT_>
96 static void cublas_axpy(DT_* r, DT_ a, const DT_* x, Index size, cudaDataType_t dt)
97 {
98 cublasStatus_t status = cublasAxpyEx(Util::Intern::cublas_handle, int(size), &a, dt, x, dt, 1, r, dt, 1, dt);
99 if (status != CUBLAS_STATUS_SUCCESS)
100 throw InternalError(__func__, __FILE__, __LINE__, "cuda error: " + stringify(cublasGetStatusString(status)));
101 }
102
103 template<typename DT_>
104 static void cuda_sync_dot(DT_* result, DT_* device_helper, const DT_* x, const DT_* y, const DT_* freqs, Index size, const Dist::Comm& comm, cudaStream_t stream = 0)
105 {
106 cudaCheck(cudaMemsetAsync(device_helper, 0, sizeof(DT_)), "cudaMemSetAsync");
107 constexpr Index blocksize = 512u;
108 dim3 grid;
109 dim3 block;
110 block.x = (unsigned)blocksize;
111 grid.x = (unsigned)ceil((size)/(double)(block.x*2*10));
112 LAFEM::Arch::cuda_triple_dot<DT_, blocksize><<<grid, block, blocksize*sizeof(DT_), stream>>>(device_helper, x, size, y, freqs);
113 cudaCheck(cudaMemcpyAsync(result, device_helper, sizeof(DT_), cudaMemcpyDeviceToHost, stream), "cudaMemCpy");
114 cudaStreamSynchronize(stream);
115 comm.allreduce(result, result, 1u, Dist::op_sum);
116 }
117
118 template <typename DT_, typename IT_>
119 __global__ void cuda_unit_filter_def(DT_ * v, const IT_ * sv_indices, const Index ue)
120 {
121 Index idx = threadIdx.x + blockDim.x * blockIdx.x;
122 // grid strided for loop
123 for(int i = idx; i < ue; i += blockDim.x * gridDim.x)
124 {
125 v[sv_indices[i]] = DT_(0);
126 }
127 }
128
129 template <typename DT_>
130 __global__ void cuda_ComponentProduct(DT_ * r, const DT_ * x, const DT_ * y, const Index count)
131 {
132 Index idx = threadIdx.x + blockDim.x * blockIdx.x;
133 for(Index i = idx; i < count; i += Index(blockDim.x*gridDim.x))
134 r[i] = x[i] * y[i];
135 }
136
137 /**
138 * \brief Performs m[k] = alpha * (A*rhs)[k_j] + beta * m[k]
139 * where k_j is the actual sparse mirror index
140 */
141 template<typename DT_, typename IT_>
142 __global__ void calculate_mirror_entries(DT_* __restrict__ mirror_buffer, const IT_* __restrict__ mirror_indx, const Index mirror_size, const IT_* __restrict__ row_ptr, const IT_* __restrict__ colidx, const DT_* values, const DT_* rhs, DT_ alpha, DT_ beta)
143 {
144 Index idx = Index(threadIdx.x + blockDim.x * blockIdx.x);
145 // grid strided for loop
146 for(Index i = idx; i < mirror_size; i += Index(blockDim.x * gridDim.x))
147 {
148 DT_ val = DT_(0);
149 //TODO: retry with fixed kernel, index was wrong before...
150 for(Index k = row_ptr[mirror_indx[i]]; k < row_ptr[mirror_indx[i]+1]; ++k)
151 {
152 val += values[k] * rhs[colidx[k]];
153 }
154 mirror_buffer[i] = alpha * val + beta * mirror_buffer[i];
155 }
156 }
157
158 template<typename DT_, typename IT_>
159 __global__ void gather_mirror_entries(DT_* __restrict__ mirror_buffer, const IT_* __restrict__ mirror_indx, const Index mirror_size, const DT_* __restrict__ vec)
160 {
161 Index idx = Index(threadIdx.x + blockDim.x * blockIdx.x);
162 // grid strided for loop
163 for(Index i = idx; i < mirror_size; i += Index(blockDim.x * gridDim.x))
164 {
165 mirror_buffer[i] = vec[mirror_indx[i]];
166 }
167 }
168
169 template<typename DT_, typename IT_>
170 __global__ void scatter_mirror_entries(DT_* __restrict__ vec, DT_* __restrict__ mirror_buffer, const IT_* __restrict__ mirror_indx, const Index mirror_size)
171 {
172 Index idx = Index(threadIdx.x + blockDim.x * blockIdx.x);
173 // grid strided for loop
174 for(Index i = idx; i < mirror_size; i += Index(blockDim.x * gridDim.x))
175 {
176 // to allow for asynchronizity by using atomics
177 cuda::atomic_ref<DT_, cuda::thread_scope_device> val(vec[mirror_indx[i]]);
178 val.fetch_add(mirror_buffer[i]);
179 }
180 }
181
182 template<typename DT_, typename IT_>
183 static void apply_def_filter(DT_* vec, const IT_* filter_idx, Index filter_ue, Index blocksize, Index gridsize)
184 {
185 // and filter
186 dim3 grid, block;
187 block.x = (unsigned)blocksize;
188 grid.x = (unsigned)gridsize;
189 cuda_unit_filter_def<<<grid, block>>>(vec, filter_idx, filter_ue);
190 cudaCheckLastErr()
191 }
192
193 template<typename DT_>
194 static void scale_vec(DT_* r, const DT_* x, const DT_* y, Index size, cudaStream_t stream = 0)
195 {
196 Index blocksize = Util::cuda_blocksize_axpy;
197 dim3 grid;
198 dim3 block;
199 block.x = (unsigned)blocksize;
200 // in theory, this should be num_rows
201 grid.x = (unsigned)ceil((size)/(double)(block.x));
202
203 cuda_ComponentProduct<<<grid, block, 0, stream>>>(r, x, y, size);
204 cudaCheckLastErr()
205 }
206
207 template<typename DT_>
208 static void calculate_batched_dots(DT_* dots, const DT_* target, DT_ const * const* device_elements, Index dot_size, Index num_dots)
209 {
210 constexpr Index blocksize = 256u;
211 // constexpr Index blocksize = 32u;
212 constexpr int num_batch = 4;
213 dim3 grid;
214 dim3 block;
215 block.x = (unsigned)blocksize;
216 block.y = num_batch;
217 grid.x = (unsigned)ceil((dot_size)/(double)(block.x*2*10));
218 grid.y = (unsigned)ceil((num_dots)/(double)(block.y));
219 LAFEM::Arch::cuda_batched_dot<DT_, blocksize><<<grid, block, blocksize*num_batch*sizeof(DT_)>>>(dots, target, dot_size, device_elements, num_dots);
220 cudaCheckLastErr()
221 }
222
223 template<typename DT_>
224 static void calculate_synced_batched_dots(DT_* dot_helper, DT_* dot_helper_device, const DT_* target, DT_ const * const* device_elements, DT_ const * const freqs, Index dot_size, Index num_dots, const Dist::Comm& comm, cudaStream_t stream = 0)
225 {
226 constexpr Index blocksize = 256u;
227 // constexpr Index blocksize = 32u;
228 constexpr int num_batch = 4;
229 dim3 grid;
230 dim3 block;
231 block.x = (unsigned)blocksize;
232 block.y = num_batch;
233 grid.x = (unsigned)ceil((dot_size)/(double)(block.x*2*10));
234 grid.y = (unsigned)ceil((num_dots)/(double)(block.y));
235 cudaCheck(cudaMemsetAsync(dot_helper_device, 0, size_t(num_dots)*sizeof(DT_), stream), "cudaMemsetAsync");
236 LAFEM::Arch::cuda_batched_triple_dot<DT_, blocksize><<<grid, block, blocksize*num_batch*sizeof(DT_), stream>>>(dot_helper_device, target, dot_size, device_elements, freqs, num_dots);
237 cudaCheckLastErr()
238 cudaCheck(cudaMemcpyAsync(dot_helper, dot_helper_device, size_t(num_dots)*sizeof(DT_), cudaMemcpyDeviceToHost, stream), "cudaMemcpyAsync");
239 cudaStreamSynchronize(stream);
240 cudaCheckLastErr()
241 comm.allreduce(dot_helper, dot_helper, num_dots, Dist::op_sum);
242 }
243
244 template<typename DT_>
245 static void add_vecs(DT_* vec_v, DT_ const* const * device_elements, const DT_* dots, Index vec_size, Index num_axpy, DT_ alpha)
246 {
247 if(vec_size == Index(0))
248 return;
249 constexpr Index blocksize = 128u;
250 dim3 grid;
251 dim3 block;
252 block.x = (unsigned)blocksize;
253 // one block always does a warp size chunk of target (due to load coalescing)
254 grid.x = static_cast<unsigned int>((vec_size+32u-1u)/32u);
255 LAFEM::Arch::cuda_cumulative_axpy<DT_, blocksize><<<grid, block, blocksize*sizeof(DT_)>>>(vec_v, vec_size, device_elements, dots, num_axpy, alpha);
256 cudaCheckLastErr()
257 }
258
259
260 template<typename DT_, typename IT_>
261 __global__ void cuda_compare(const DT_* mirror_buffer, const IT_* mirror_indx, Index num_mirror, const DT_* vec_sol)
262 {
263 constexpr DT_ tol = DT_(1E-8);
264 Index idx = threadIdx.x + blockDim.x * blockIdx.x;
265 if(idx >= num_mirror)
266 return;
267 std::printf("Working, values %f, %f, %lu, %lu\n", mirror_buffer[idx], vec_sol[mirror_indx[idx]], idx, Index(mirror_indx[idx]));
268 if(abs(mirror_buffer[idx] - vec_sol[mirror_indx[idx]]) > tol)
269 std::printf("Error, values %f, %f, %lu, %lu larger\n", mirror_buffer[idx], vec_sol[mirror_indx[idx]], idx, Index(mirror_indx[idx]));
270 }
271
272 /// global r = a*A*x product be careful about setting b correctly, since this factor adds r
273 template<typename DT_, typename IT_, typename Gate_, std::size_t st_>
274 CUDA_HOST void apply_synced_mat(std::vector<DT_*>& buffer_host, std::vector<DT_*>& buffer_device, DT_* r, cusparseDnVecDescr_t dr, const DT_* x, cusparseDnVecDescr_t dx,
275 const Gate_& gate, cusparseOperation_t op, cudaDataType_t ct, const CuMatDesc& mat_desc, const CSRHelper::CRSMat<DT_, IT_>& mat, DT_ alpha, DT_ beta, cudaStream_t main_stream, const std::array<cudaStream_t, st_>& streams)
276 {
277 // fill mirror buffers, first gather values
278 const auto& mirrors = gate.get_mirrors();
279 const auto& ranks = gate.get_ranks();
280 const auto& comm = *gate.get_comm();
281 const std::size_t n = ranks.size();
282 // acquire device views of the mirror index arrays; kept alive for the whole exchange
283 std::vector<Memory::TypedView<IT_>> mirror_idx_views;
284 mirror_idx_views.reserve(n);
285 for(std::size_t k = 0; k < n; ++k)
286 mirror_idx_views.emplace_back(mirrors[k].indices_view_r(Memory::Location::cuda));
287 // Index s_id = 0;
288 // for(Index k = 0; k < n; ++k)
289 // {
290 // dim3 block;
291 // dim3 grid;
292 // block.x = (unsigned)64;
293 // grid.x = (unsigned)ceil((mirrors.at(k).num_indices())/(double)((block.x)));
294 // gather_mirror_entries<<<grid, block, 0, streams[s_id]>>>(buffer_device[k], mirrors[k].indices(), mirrors[k].num_indices(), r);
295 // cudaDeviceSynchronize();
296 // cudaCheckLastErr()
297 // calculate_mirror_entries<<<grid, block, 0, streams[s_id]>>>(buffer_device[k], mirrors[k].indices(), mirrors[k].num_indices(), mat.row, mat.col, mat.val, x, alpha, beta);
298 // cudaDeviceSynchronize();
299 // cudaCheckLastErr()
300 // cudaCheck(cudaMemcpyAsync(buffer_host[2*k], buffer_device[k], mirrors[k].num_indices()*sizeof(DT_), cudaMemcpyDeviceToHost, streams[s_id]), "cudaMemcpyAsync");
301 // s_id = (s_id + 1u)%streams.size();
302 // }
303 // cudaDeviceSynchronize();
304 // cudaCheckLastErr()
305 // start cusparse
306 apply_cu_spmv(op, ct, dx, dr, mat_desc, alpha, beta);
307
308 cudaDeviceSynchronize();
309 Index s_id = 0;
310 for(Index k = 0; k < n; ++k)
311 {
312 dim3 block;
313 dim3 grid;
314 block.x = (unsigned)64;
315 grid.x = (unsigned)ceil((mirrors.at(k).num_indices())/(double)((block.x)));
316 gather_mirror_entries<<<grid, block, 0, streams[s_id]>>>(buffer_device[k], mirror_idx_views[k].get_r(), mirrors[k].num_indices(), r);
317 // cudaDeviceSynchronize();
318 // cudaCheckLastErr()
319 // calculate_mirror_entries<<<grid, block, 0, streams[s_id]>>>(buffer_device[k], mirrors[k].indices(), mirrors[k].num_indices(), mat.row, mat.col, mat.val, x, alpha, beta);
320 // cudaDeviceSynchronize();
321 // cudaCheckLastErr()
322 cudaCheck(cudaMemcpyAsync(buffer_host[2*k], buffer_device[k], mirrors[k].num_indices()*sizeof(DT_), cudaMemcpyDeviceToHost, streams[s_id]), "cudaMemcpyAsync");
323 s_id = (s_id + 1u)%streams.size();
324 }
325 // cudaDeviceSynchronize();
326 // cudaCheckLastErr()
327 // compare entries
328 // for(Index k = 0; k < n; ++k)
329 // {
330 // std::printf("Using mirror of size %lu \n", mirrors.at(k).num_indices());
331 // const auto& mirr_indx = mirrors.at(k).indices();
332 // for(Index l = 0; l < mirrors.at(k).num_indices(); ++l)
333 // {
334 // if(Math::abs(r[mirr_indx[l]] - buffer_host[k][l]) > DT_(1E-3))
335 // {
336 // std::printf("Err between r %f, m %f, at idx %lu, mirr %lu \n", r[mirr_indx[l]], buffer_host[k][l], Index(mirr_indx[l]), Index(l));
337 // }
338 // }
339
340 // // dim3 block;
341 // // dim3 grid;
342 // // block.x = (unsigned)64;
343 // // grid.x = (unsigned)ceil((mirrors.at(k).num_indices())/(double)((block.x)));
344 // // cuda_compare<<<grid, block, 0>>>(buffer_device[k], mirrors[k].indices(), mirrors[k].num_indices(), r);
345 // // cudaDeviceSynchronize();
346 // // cudaCheckLastErr()
347 // }
348
349 Dist::RequestVector _send_reqs, _recv_reqs;
350 // post receives
351 _recv_reqs.reserve(n);
352 for(std::size_t i(0); i < n; ++i)
353 {
354 // post receive
355 _recv_reqs.push_back(comm.irecv(buffer_host.at(2u*i+1), mirrors.at(i).num_indices(), ranks.at(i)));
356 }
357
358 // post sends
359 _send_reqs.reserve(n);
360
361 // wait for stream to finish and push send
362 s_id = 0;
363 for(std::size_t i(0); i < n; ++i)
364 {
365 // wait for stream to finish
366 cudaStreamSynchronize(streams[s_id]);
367 // post send
368 _send_reqs.push_back(comm.isend(buffer_host.at(2u*i), mirrors.at(i).num_indices(), ranks.at(i)));
369 s_id = (s_id + 1u)%streams.size();
370 }
371
372 // wait for sync to finish and copy back to device
373 // process all pending receives
374 s_id = 0;
375 for(std::size_t idx(0u); _recv_reqs.wait_any(idx); )
376 {
377 // copy the buffer
378 cudaCheck(cudaMemcpyAsync(buffer_device[idx], buffer_host[2*idx+1], mirrors[idx].num_indices()*sizeof(DT_), cudaMemcpyHostToDevice, streams[s_id]), "cudaMemcpyAsync");
379 s_id = (s_id + 1u)%streams.size();
380 }
381
382 //wait for all streams to finish
383 cudaDeviceSynchronize();
384 cudaCheckLastErr()
385
386 s_id = 0;
387 // and now, add
388 for(Index k = 0; k < n; ++k)
389 {
390 dim3 block;
391 dim3 grid;
392 block.x = (unsigned)64;
393 grid.x = (unsigned)ceil((mirrors.at(k).num_indices())/(double)((block.x)));
394 scatter_mirror_entries<<<grid, block, 0, streams[s_id]>>>(r, buffer_device[k], mirror_idx_views[k].get_r(), mirrors[k].num_indices());
395 //TODO: stream iter missing...
396 }
397 cudaCheckLastErr()
398
399 // wait for all sends to finish
400 _send_reqs.wait_all();
401 }
402 }
403
404
405 template<typename DT_>
406 static FEAT::Solver::Status _analyze_defect(CSRHelper::GMRESStatus<DT_>& stat, DT_ def_prev, DT_ def_init, Index max_iter, Index min_iter, DT_ tol_abs, DT_ tol_rel)
407 {
408 using FEAT::Solver::Status;
409 // ensure that the defect is neither NaN nor infinity
410 if(!Math::isfinite(stat.def_norm))
411 return Status::aborted;
412
413 // // is diverged?
414 // if(this->is_diverged(def_cur))
415 // return Status::diverged;
416
417 // maximum number of iterations performed?
418 if(stat.num_iter >= max_iter)
419 return Status::max_iter;
420
421 // minimum number of iterations performed?
422 if(stat.num_iter < min_iter)
423 return Status::progress;
424
425 // is converged?
426 if((stat.def_norm <= tol_abs) && ((stat.def_norm <= (tol_rel * def_init))))
427 return Status::success;
428
429 // // check for stagnation?
430 // if(check_stag && (this->_min_stag_iter > Index(0)))
431 // {
432 // // did this iteration stagnate?
433 // if(def_cur >= this->_stag_rate * def_prev)
434 // {
435 // // increment stagnation count
436 // if(++this->_num_stag_iter >= this->_min_stag_iter)
437 // return Status::stagnated;
438 // }
439 // else
440 // {
441 // // this iteration did not stagnate
442 // this->_num_stag_iter = Index(0);
443 // }
444 // }
445
446 // continue iterating
447 return Status::progress;
448 }
449
450 template<typename DT_, typename IT_>
451 FEAT::Solver::Status cuda_apply_amavanka_gmres_seq(Memory::Arbiter& vec_sol_arb, const Memory::Arbiter& vec_rhs_arb, const CSRHelper::GMRESApplyInfo<DT_, IT_>& apply_info, CSRHelper::GMRESStatus<DT_>& status)
452 {
453 using namespace FEAT;
454 const auto id_setup = Util::cuda_start_range("GMRES Setup");
455 // extract info
456 const Index rows = apply_info.size;
457 const Index columns = apply_info.size;
458
459 // --- acquire device (cuda) views for all arbiter-backed data; these views are kept alive for the
460 // entire solve so the resolved device pointers stay valid, and are released on function return ---
461 Memory::TypedView<DT_> vec_sol_view(vec_sol_arb.view(Memory::Location::cuda, Memory::Access::read_write));
462 DT_* vec_sol = vec_sol_view.get_w();
463 Memory::TypedView<DT_> vec_rhs_view(vec_rhs_arb.view(Memory::Location::cuda, Memory::Access::read));
464 const DT_* vec_rhs = vec_rhs_view.get_r();
465
466 // matrix value/row/column device pointers (read views) and the nnz counts (read from a main view)
467 Memory::View sys_val_view(apply_info.mat_sys.val->view(Memory::Location::cuda, Memory::Access::read));
468 Memory::View sys_row_view(apply_info.mat_sys.row->view(Memory::Location::cuda, Memory::Access::read));
469 Memory::View sys_col_view(apply_info.mat_sys.col->view(Memory::Location::cuda, Memory::Access::read));
470 Memory::View vanka_val_view(apply_info.mat_vanka.val->view(Memory::Location::cuda, Memory::Access::read));
471 Memory::View vanka_row_view(apply_info.mat_vanka.row->view(Memory::Location::cuda, Memory::Access::read));
472 Memory::View vanka_col_view(apply_info.mat_vanka.col->view(Memory::Location::cuda, Memory::Access::read));
473
474 // krylov basis vectors: collect device pointers (read-write) into a host array, keep views alive
475 const std::vector<Memory::Arbiter*>& vec_v_arbs = *apply_info.vec_v;
476 std::vector<Memory::TypedView<DT_>> vec_v_views;
477 vec_v_views.reserve(vec_v_arbs.size());
478 std::vector<DT_*> vec_v_host(vec_v_arbs.size());
479 for(std::size_t k = 0; k < vec_v_arbs.size(); ++k)
480 {
481 vec_v_views.emplace_back(vec_v_arbs[k]->view(Memory::Location::cuda, Memory::Access::read_write));
482 vec_v_host[k] = vec_v_views[k].get_w();
483 }
484 // const Index used_elements_def = Index(apply_info.mat_sys.row[rows]);
485 // const Index used_elements_vanka = Index(apply_info.mat_vanka.row[rows]);
486 // create necessary data arrays on host and device
487 // setup workspace for cusparse matrices
488 cusparseOperation_t trans = CUSPARSE_OPERATION_NON_TRANSPOSE;
489 cudaDataType dt;
490 cudaDataType ct; //compute type
491 if (typeid(DT_) == typeid(double))
492 {
493 dt = CUDA_R_64F;
494 ct = CUDA_R_64F;
495 }
496 else if (typeid(DT_) == typeid(float))
497 {
498 dt = CUDA_R_32F;
499 ct = CUDA_R_32F;
500 }
501 cusparseIndexType_t it;
502 if(sizeof(IT_) == 4u)
503 it = CUSPARSE_INDEX_32I;
504 else if(sizeof(IT_) == 8u)
505 it = CUSPARSE_INDEX_64I;
506 cusparseStatus_t cu_status;
507 const DT_ defect_alpha = DT_(-1);
508 const DT_ defect_beta = DT_(1);
509 const DT_ vanka_alpha = DT_(1);
510 const DT_ vanka_beta = DT_(0);
511 const DT_ abs_tol = apply_info.abs_tol;
512 const DT_ rel_tol = apply_info.rel_tol;
513 const DT_ inner_res_scale = apply_info.res_scale;
514 const Index krylov_dim = apply_info.krylov_dim;
515 const Index max_iter = apply_info.max_iter;
516 const Index min_iter = apply_info.min_iter;
517
518 const Index plot_interval = apply_info.plot_interval;
519 const Solver::PlotMode plot_mode = apply_info.plot_mode;
520
521 cusparseDnVecDescr_t dx;
522 {
523 cu_status = cusparseCreateDnVec(&dx, columns, (void*)vec_sol, dt);
524 if (cu_status != CUSPARSE_STATUS_SUCCESS)
525 throw InternalError(__func__, __FILE__, __LINE__, "cuda error: " + stringify(cusparseGetErrorString(cu_status)));
526 }
527
528 cusparseDnVecDescr_t dr;
529 {
530 cu_status = cusparseCreateDnVec(&dr, columns, (void*)vec_rhs, dt);
531 if (cu_status != CUSPARSE_STATUS_SUCCESS)
532 throw InternalError(__func__, __FILE__, __LINE__, "cuda error: " + stringify(cusparseGetErrorString(cu_status)));
533 }
534
535 CuMatDesc cumat_sys;
536 Intern::alloc_cusparse_interface<DT_, IT_>(trans, dt, ct, it, dx, dr, sys_row_view.raw_r(), sys_col_view.raw_r(), sys_val_view.raw_r(),
537 apply_info.mat_sys.num_rows, apply_info.mat_sys.num_cols, apply_info.mat_sys.num_nnz, cumat_sys, defect_alpha, defect_beta);
538
539 CuMatDesc cumat_vanka;
540 Intern::alloc_cusparse_interface<DT_, IT_>(trans, dt, ct, it, dx, dr, vanka_row_view.raw_r(), vanka_col_view.raw_r(), vanka_val_view.raw_r(),
541 apply_info.mat_vanka.num_rows, apply_info.mat_vanka.num_cols, apply_info.mat_vanka.num_nnz, cumat_vanka, vanka_alpha, vanka_beta);
542
543 // allocations for helper arrays
544 const Index gauss_size = krylov_dim * (krylov_dim+1u) / 2u;
545 DT_ *_c, *_s, *_q, *_h;
546 cudaCheck(cudaMallocHost(&_c, size_t(krylov_dim)*sizeof(DT_)), "cudaMallocHost");
547 cudaCheck(cudaMallocHost(&_s, size_t(krylov_dim)*sizeof(DT_)), "cudaMallocHost");
548 cudaCheck(cudaMallocHost(&_q, size_t(krylov_dim+1)*sizeof(DT_)), "cudaMallocHost");
549 cudaCheck(cudaMallocHost(&_h, size_t(gauss_size)*sizeof(DT_)), "cudaMallocHost");
550 // DT_ *_c_d, *_s_d, *_q_d, *_h_d;
551 DT_ *_q_d, *_h_d;
552 // cudaCheck(cudaMalloc(&_c_d, size_t(krylov_dim)*sizeof(DT_)), "cudaMalloc");
553 // cudaCheck(cudaMalloc(&_s_d, size_t(krylov_dim)*sizeof(DT_)), "cudaMalloc");
554 cudaCheck(cudaMalloc(&_q_d, size_t(krylov_dim+1)*sizeof(DT_)), "cudaMalloc");
555 cudaCheck(cudaMalloc(&_h_d, size_t(gauss_size)*sizeof(DT_)), "cudaMalloc");
556 // scratch for the batched projection dots plus the appended self-dot (krylov_dim projections + 1)
557 DT_ *batch_dots_h, *batch_dots_d;
558 cudaCheck(cudaMallocHost(&batch_dots_h, size_t(krylov_dim+1)*sizeof(DT_)), "cudaMallocHost");
559 cudaCheck(cudaMalloc(&batch_dots_d, size_t(krylov_dim+1)*sizeof(DT_)), "cudaMalloc");
560 DT_** vec_v = vec_v_host.data();
561 Memory::TypedView<DT_> vec_w_view(apply_info.vec_w->view(Memory::Location::cuda, Memory::Access::read_write));
562 DT_* vec_w = vec_w_view.get_w();
563 DT_** vec_v_d;
564 cudaCheck(cudaMalloc(&vec_v_d, size_t(krylov_dim+1)*sizeof(DT_*)), "cudaMalloc");
565
566 if(apply_info.prefetch_data)
567 {
568 cudaMemLocation location;
569 {location.type = cudaMemLocationTypeDevice; location.id = FEAT::Util::cuda_get_device_id();}
570 // hint to prefetch vector data, if possible
571 for(Index k = 0; k < krylov_dim+1; ++k)
572 {
573 cudaMemPrefetchAsync(vec_v[k], rows*sizeof(DT_), location, 0);
574 }
575 }
576
577 // cudaCheck(cudaMemsetAsync(_c_d, 0, size_t(krylov_dim)*sizeof(DT_)), "memsetAsync");
578 // cudaCheck(cudaMemsetAsync(_s_d, 0, size_t(krylov_dim)*sizeof(DT_)), "memsetAsync");
579 cudaCheck(cudaMemsetAsync(_q_d, 0, size_t(krylov_dim+1)*sizeof(DT_)), "memsetAsync");
580
581 cudaCheck(cudaMemcpyAsync(vec_v_d, vec_v, size_t(krylov_dim+1)*sizeof(DT_*), cudaMemcpyHostToDevice), "memcopyAsync");
582
583 std::uninitialized_fill(_c, _c+krylov_dim, DT_(0));
584 std::uninitialized_fill(_s, _s+krylov_dim, DT_(0));
585 std::uninitialized_fill(_q, _q+krylov_dim+1u, DT_(0));
586 std::uninitialized_fill(_h, _h+gauss_size, DT_(0));
587
588 cudaDeviceSynchronize();
589 Util::cuda_check_last_error();
590
591 // initialize defect
592 DT_ def_init = DT_(0);
593 DT_ def_prev = DT_(0);
594 DT_ def_cur = DT_(0);
595
596
597 // calculate norm
598 Intern::cublas_dot(def_init, vec_v[0], vec_v[0], rows, dt);
599 cudaDeviceSynchronize();
600 Util::cuda_check_last_error();
601
602 def_init = Math::sqrt(def_init);
603 status.def_init = def_init;
604
605
606 def_prev = def_cur = def_init;
607
608 status.def_norm = def_cur;
609 status.num_iter = 0u;
610 FEAT::Solver::Status solver_status = FEAT::Solver::Status::progress;
611
612 Memory::TypedView<IT_> filter_idx_view(apply_info.def_filter.ind->view(Memory::Location::cuda, Memory::Access::read));
613 const IT_* filter_idx = filter_idx_view.get_r();
614 const Index filter_ue = apply_info.def_filter.used_elements;
615 const Index blocksize = Util::cuda_blocksize_misc;
616 const Index filter_gridsize = Index(ceil((filter_ue)/(double)(blocksize)));
617
618
619 if(!Math::isfinite(def_init))
620 solver_status = FEAT::Solver::Status::aborted;
621
622 Util::cuda_stop_range(id_setup);
623
624 const auto id_outer = Util::cuda_start_range("GMRES Outer Loop");
625 while(solver_status == FEAT::Solver::Status::progress)
626 {
627 // reset h device
628 cudaCheck(cudaMemsetAsync(_h_d, 0, size_t(gauss_size)*sizeof(DT_)), "memsetAsync");
629 // set first _q
630 _q[0] = def_cur;
631 // cudaCheck(cudaMemcpyAsync(_q_d, _q, sizeof(DT_), cudaMemcpyHostToDevice), "cudaMemcopyAsync");
632 // normalize v[0]
633 Intern::cublas_scale(vec_v[0], DT_(1)/_q[0], rows, dt);
634 // reset h
635 std::fill(_h, _h+gauss_size, DT_(0));
636
637 const auto id_inner = Util::cuda_start_range("Inner GMRES Loop");
638 Index i(0);
639 Index h_offset(0);
640 while(i < krylov_dim)
641 {
642 const auto first_section = Util::cuda_start_range("First Section");
643 // apply vanka matrix
644 {
645 cu_status = cusparseDnVecSetValues(dx, (void*)vec_v[i]);
646 if (cu_status != CUSPARSE_STATUS_SUCCESS)
647 throw InternalError(__func__, __FILE__, __LINE__, "cuda error: " + stringify(cusparseGetErrorString(cu_status)));
648 cu_status = cusparseDnVecSetValues(dr, (void*)vec_w);
649 if (cu_status != CUSPARSE_STATUS_SUCCESS)
650 throw InternalError(__func__, __FILE__, __LINE__, "cuda error: " + stringify(cusparseGetErrorString(cu_status)));
651
652 Intern::apply_cu_spmv(trans, ct, dx, dr, cumat_vanka, vanka_alpha, vanka_beta);
653 // and filter
654 Intern::apply_def_filter(vec_w, filter_idx, filter_ue, blocksize, filter_gridsize);
655 }
656
657 // calculate defect
658 {
659 // reuse dr
660 cu_status = cusparseDnVecSetValues(dx, (void*)vec_v[i+1]);
661 if (cu_status != CUSPARSE_STATUS_SUCCESS)
662 throw InternalError(__func__, __FILE__, __LINE__, "cuda error: " + stringify(cusparseGetErrorString(cu_status)));
663 Intern::apply_cu_spmv(trans, ct, dr, dx, cumat_sys, DT_(1), DT_(0));
664 Intern::apply_def_filter(vec_v[i+1], filter_idx, filter_ue, blocksize, filter_gridsize);
665 }
666
667 // Gram-Schmidt process (classical / conditional CGS2) with the self-dot fused into the
668 // batched reduction: request i+2 dots so slot i+1 (vec_v_d has krylov_dim+1 pointers) holds
669 // <v[i+1], v[i+1]>, from which the orthogonalized norm is recovered algebraically.
670 DT_ alpha = DT_(0);
671 {
672 // the batched dot kernel accumulates atomically, so zero the scratch first
673 cudaCheck(cudaMemsetAsync(batch_dots_d, 0, size_t(i+2)*sizeof(DT_)), "memsetAsync");
674 Intern::calculate_batched_dots(batch_dots_d, vec_v[i+1], vec_v_d, rows, i+2);
675 cudaCheck(cudaMemcpyAsync(batch_dots_h, batch_dots_d, size_t(i+2)*sizeof(DT_), cudaMemcpyDeviceToHost), "cudaMemcopyAsync");
676 cudaDeviceSynchronize();
677 Util::cuda_check_last_error();
678 // subtract the projection (reads the leading i+1 scale entries)
679 Intern::add_vecs(vec_v[i+1], vec_v_d, batch_dots_d, rows, i+1, DT_(-1));
680
681 // store projections into the Hessenberg column and recover the norm algebraically
682 DT_ sum_sqr = DT_(0);
683 for(Index k = 0; k < i+1; ++k)
684 {
685 _h[h_offset + k] = batch_dots_h[k];
686 sum_sqr += Math::sqr(batch_dots_h[k]);
687 }
688 const DT_ self_dot = batch_dots_h[i+1];
689 DT_ nrm_sqr = self_dot - sum_sqr;
690
691 // conditional corrective reorthogonalization (cgs2); the second batched reduction supplies
692 // both the corrections and the updated self-dot, so no extra reduction is needed
693 if((apply_info.ortho_type == FEAT::Solver::KrylovOrthogonalizerType::cgs2)
694 && (apply_info.force_reortho || (nrm_sqr < Math::sqr(apply_info.reortho_tol) * self_dot)))
695 {
696 cudaCheck(cudaMemsetAsync(batch_dots_d, 0, size_t(i+2)*sizeof(DT_)), "memsetAsync");
697 Intern::calculate_batched_dots(batch_dots_d, vec_v[i+1], vec_v_d, rows, i+2);
698 cudaCheck(cudaMemcpyAsync(batch_dots_h, batch_dots_d, size_t(i+2)*sizeof(DT_), cudaMemcpyDeviceToHost), "cudaMemcopyAsync");
699 cudaDeviceSynchronize();
700 Util::cuda_check_last_error();
701 Intern::add_vecs(vec_v[i+1], vec_v_d, batch_dots_d, rows, i+1, DT_(-1));
702 DT_ sum_sqr2 = DT_(0);
703 for(Index k = 0; k < i+1; ++k)
704 {
705 _h[h_offset + k] += batch_dots_h[k];
706 sum_sqr2 += Math::sqr(batch_dots_h[k]);
707 }
708 nrm_sqr = batch_dots_h[i+1] - sum_sqr2;
709 }
710
711 // recover the norm; fall back to an explicit dot on heavy cancellation (guarantees a
712 // positive result so the subsequent normalization cannot produce a NaN)
713 if(nrm_sqr <= Math::Limits<DT_>::epsilon() * DT_(100))
714 {
715 Intern::cublas_dot(nrm_sqr, vec_v[i+1], vec_v[i+1], rows, dt);
716 cudaDeviceSynchronize();
717 Util::cuda_check_last_error();
718 nrm_sqr = Math::abs(nrm_sqr);
719 }
720 alpha = Math::sqrt(nrm_sqr);
721 }
722 Util::cuda_stop_range(first_section);
723 { // open "Second Section" scope; RAII so the convergence/max-iter break below still closes it
724 FEAT::Util::ScopedNvtxRange _second_section("Second Section");
725 Intern::cublas_scale(vec_v[i+1], DT_(1)/alpha, rows, dt);
726 {
727 const auto id_givens = Util::cuda_start_range("Givens Rotation");
728 // apply Givens rotations
729 for(Index k(0); k < i; ++k)
730 {
731 DT_* h_i = _h + h_offset;
732 const DT_ t(h_i[k]);
733 h_i[k] = _c[k] * t + _s[k] * h_i[k+1];
734 h_i[k+1] = _s[k] * t - _c[k] * h_i[k+1];
735 }
736 Util::cuda_stop_range(id_givens);
737 }
738
739 const auto id_def_push = Util::cuda_start_range("Push defect");
740 // compute beta
741 const DT_ beta = Math::sqrt(Math::sqr(_h[h_offset+i]) + Math::sqr(alpha));
742
743 // compute next plane rotation
744 _s[i] = alpha / beta;
745 _c[i] = _h[h_offset+i] / beta;
746
747 // important: back sync h -> h device not required
748 _h[h_offset+i] = beta;
749 _q[i+1] = _s[i] * _q[i];
750 _q[i] *= _c[i];
751 h_offset += i+1;
752
753 Util::cuda_stop_range(id_def_push);
754 // push our new defect
755 if(++i < krylov_dim)
756 {
757 // get the absolute defect
758 def_cur = Math::abs(_q[i]);
759
760 // // did we diverge?
761 // if((def_cur > div_abs) || (def_cur > (div_rel * def_init)))
762 // break;
763
764 // minimum number of iterations performed?
765 if(!(status.num_iter < min_iter))
766 {
767 // did we converge?
768 if((def_cur <= inner_res_scale * abs_tol) && ((def_cur <= inner_res_scale * (rel_tol * def_init))))
769 break;
770
771 // maximum number of iterations performed?
772 if(status.num_iter >= max_iter)
773 break;
774 }
775
776 ++status.num_iter;
777 status.def_norm = def_cur;
778 // plot?
779 if((plot_mode == Solver::PlotMode::iter || plot_mode == Solver::PlotMode::all) && status.num_iter%plot_interval == 0u)
780 {
781 FEAT::String msg = FEAT::String("CudaGMRES")
782 + "* " + stringify(status.num_iter).pad_front(4)
783 + " : " + stringify_fp_sci(def_cur);
784 std::cout << msg << "\n";
785 }
786 }
787
788 } // close "Second Section" scope (RAII)
789 }
790 Util::cuda_stop_range(id_inner);
791
792 const auto id_update = Util::cuda_start_range("Update Solution");
793 {
794 const Index n = Math::min(i, krylov_dim);
795 const auto id_h_solve = Util::cuda_start_range("Solve Hessenberg");
796 // solve H*q = q
797 for(Index k(n); k > 0;)
798 {
799 --k;
800 const Index h_offset = (k+1)*k/2u;
801 _q[k] /= _h[h_offset + k];
802 for(Index j(k); j > 0;)
803 {
804 --j;
805 _q[j] -= _h[h_offset + j] * _q[k];
806 }
807 }
808 Util::cuda_stop_range(id_h_solve);
809 // copy _q values
810 cudaCheck(cudaMemcpyAsync(_q_d, _q, size_t(n)*sizeof(DT_), cudaMemcpyHostToDevice), "cudaMemcpyAsync");
811
812 // Runtime::SyncGuard sync_guard;
813 // update solution
814 cudaCheck(cudaMemsetAsync(vec_w, 0, rows*sizeof(DT_)), "cudaMemcpyAsync");
815 // _add_vecs(this->_vec_w, this->_vec_v, this->_q, n, DataType(1));
816 Intern::add_vecs(vec_w, vec_v_d, _q_d, rows, n, DT_(1));
817
818 // apply vanka matrix
819 {
820 cu_status = cusparseDnVecSetValues(dx, (void*)vec_w);
821 if (cu_status != CUSPARSE_STATUS_SUCCESS)
822 throw InternalError(__func__, __FILE__, __LINE__, "cuda error: " + stringify(cusparseGetErrorString(cu_status)));
823 cu_status = cusparseDnVecSetValues(dr, (void*)vec_v[0]);
824 if (cu_status != CUSPARSE_STATUS_SUCCESS)
825 throw InternalError(__func__, __FILE__, __LINE__, "cuda error: " + stringify(cusparseGetErrorString(cu_status)));
826
827 Intern::apply_cu_spmv(trans, ct, dx, dr, cumat_vanka, vanka_alpha, vanka_beta);
828 // and filter
829 Intern::apply_def_filter(vec_v[0], filter_idx, filter_ue, blocksize, filter_gridsize);
830 }
831 //update solution
832 Intern::cublas_axpy(vec_sol, DT_(1), vec_v[0], rows, dt);
833
834 // compute real residual
835 {
836 cu_status = cusparseDnVecSetValues(dx, (void*)vec_sol);
837 if (cu_status != CUSPARSE_STATUS_SUCCESS)
838 throw InternalError(__func__, __FILE__, __LINE__, "cuda error: " + stringify(cusparseGetErrorString(cu_status)));
839 // copy rhs to vec_v
840 cudaCheck(cudaMemcpyAsync(vec_v[0], vec_rhs, rows*sizeof(DT_), cudaMemcpyDeviceToDevice), "cudaMemcpyAsync");
841 // ath this point, sync 1 -> 0 necessary
842 Intern::apply_cu_spmv(trans, ct, dx, dr, cumat_sys, defect_alpha, defect_beta);
843 // and sync again...
844 Intern::apply_def_filter(vec_v[0], filter_idx, filter_ue, blocksize, filter_gridsize);
845 }
846
847 // increase iteration count
848 ++status.num_iter;
849
850 def_prev = def_cur;
851
852 // finally evaluate our defect
853 Intern::cublas_dot(def_cur, vec_v[0], vec_v[0], rows, dt);
854 cudaDeviceSynchronize();
855 Util::cuda_check_last_error();
856
857 def_cur = Math::sqrt(def_cur);
858 status.def_norm = def_cur;
859
860 solver_status = _analyze_defect(status, def_prev, def_init, max_iter, min_iter, abs_tol, rel_tol);
861 }
862 Util::cuda_stop_range(id_update);
863 }
864 Util::cuda_stop_range(id_outer);
865
866
867
868 cudaCheck(cudaFreeHost(_c), "cudaFreeHost");
869 cudaCheck(cudaFreeHost(_s), "cudaFreeHost");
870 cudaCheck(cudaFreeHost(_q), "cudaFreeHost");
871 cudaCheck(cudaFreeHost(_h), "cudaFreeHost");
872 cudaCheck(cudaFreeHost(batch_dots_h), "cudaFreeHost");
873 cudaCheck(cudaFree(batch_dots_d), "cudaFree");
874 // cudaCheck(cudaFree(_c_d), "cudaFree");
875 // cudaCheck(cudaFree(_s_d), "cudaFree");
876 cudaCheck(cudaFree(_q_d), "cudaFree");
877 cudaCheck(cudaFree(_h_d), "cudaFree");
878 cudaCheck(cudaFree(vec_v_d), "cudaFree");
879
880
881
882
883 Intern::cumat_free(cumat_sys);
884 Intern::cumat_free(cumat_vanka);
885 cusparseDestroyDnVec(dx);
886 cusparseDestroyDnVec(dr);
887
888 return solver_status;
889 }
890
891
892 template<typename DT_, typename MT_>
893 CUDA_HOST void _setup_comm_buffer(std::vector<DT_*>& host_buffer, std::vector<DT_*>& device_buffer, const std::vector<MT_>& mirrors)
894 {
895 host_buffer.resize(mirrors.size()*2u);
896 device_buffer.resize(mirrors.size());
897
898 for(Index k = 0; k < mirrors.size(); ++k)
899 {
900 cudaCheck(cudaMallocHost(&host_buffer[2*k], mirrors[k].num_indices() * sizeof(DT_)), "cudaMallocHost");
901 cudaCheck(cudaMallocHost(&host_buffer[2*k+1], mirrors[k].num_indices() * sizeof(DT_)), "cudaMallocHost");
902 cudaCheck(cudaMalloc(&device_buffer[k], mirrors[k].num_indices() * sizeof(DT_)), "cudaMalloc");
903 cudaCheck(cudaMemsetAsync(device_buffer[k], 0, mirrors[k].num_indices() * sizeof(DT_)), "memsetAsync");
904 }
905
906 for(Index k = 0; k < mirrors.size(); ++k)
907 {
908 std::uninitialized_fill(host_buffer[2*k], host_buffer[2*k]+mirrors[k].num_indices(), DT_(0));
909 std::uninitialized_fill(host_buffer[2*k+1], host_buffer[2*k+1]+mirrors[k].num_indices(), DT_(0));
910 }
911 }
912
913 /// global r = a*A*x product be careful about setting b correctly, since this factor adds r
914 template<typename DT_, typename IT_, typename Gate_, std::size_t st_>
915 CUDA_HOST void _apply_mat(std::vector<DT_*>& buffer_host, std::vector<DT_*>& buffer_device, DT_* r, cusparseDnVecDescr_t dr, const DT_* x, cusparseDnVecDescr_t dx,
916 const Gate_& gate, cusparseOperation_t op, cudaDataType_t ct, const CuMatDesc& mat_desc, const CSRHelper::CRSMat<DT_, IT_>& mat, DT_ alpha, DT_ beta, cudaStream_t main_stream, const std::array<cudaStream_t, st_>& streams)
917 {
918 cusparseStatus_t cu_status = cusparseDnVecSetValues(dx, (void*)x);
919 if (cu_status != CUSPARSE_STATUS_SUCCESS)
920 throw InternalError(__func__, __FILE__, __LINE__, "cuda error: " + stringify(cusparseGetErrorString(cu_status)));
921 cu_status = cusparseDnVecSetValues(dr, (void*)r);
922 if (cu_status != CUSPARSE_STATUS_SUCCESS)
923 throw InternalError(__func__, __FILE__, __LINE__, "cuda error: " + stringify(cusparseGetErrorString(cu_status)));
924
925 Intern::apply_synced_mat(buffer_host, buffer_device, r, dr, x, dx, gate, op, ct, mat_desc, mat, alpha, beta, main_stream, streams);
926
927 }
928
929 /// global r = a*A*x + b*y product
930 template<typename DT_, typename IT_, typename Gate_, std::size_t st_>
931 CUDA_HOST void _apply_mat(std::vector<DT_*>& buffer_host, std::vector<DT_*>& buffer_device, DT_* r, cusparseDnVecDescr_t dr, const DT_* x, cusparseDnVecDescr_t dx, const DT_* y,
932 const Gate_& gate, cusparseOperation_t op, cudaDataType_t ct, const CuMatDesc& mat_desc, const CSRHelper::CRSMat<DT_, IT_>& mat, DT_ alpha, DT_ beta, cudaStream_t main_stream, const std::array<cudaStream_t, st_>& streams)
933 {
934 // cusparseStatus_t cu_status = cusparseDnVecSetValues(dx, (void*)x);
935 // if (cu_status != CUSPARSE_STATUS_SUCCESS)
936 // throw InternalError(__func__, __FILE__, __LINE__, "cuda error: " + stringify(cusparseGetErrorString(cu_status)));
937 // cu_status = cusparseDnVecSetValues(dr, (void*)r);
938 // if (cu_status != CUSPARSE_STATUS_SUCCESS)
939 // throw InternalError(__func__, __FILE__, __LINE__, "cuda error: " + stringify(cusparseGetErrorString(cu_status)));
940
941 // scale vector with frequency
942 Memory::TypedView<DT_> freqs_view(gate.get_freqs().elements_view_r(Memory::Location::cuda));
943 const DT_* freqs = freqs_view.get_r();
944 Intern::scale_vec(r, y, freqs, mat.num_cols);
945
946 // and now call standard apply
947 _apply_mat(buffer_host, buffer_device, r, dr, x, dx, gate, op, ct, mat_desc, mat, alpha, beta, main_stream, streams);
948 }
949
950 // for schwarz type synch
951 template<typename DT_, typename IT_, typename Gate_, std::size_t st_>
952 CUDA_HOST void _apply_mat_mean(std::vector<DT_*>& buffer_host, std::vector<DT_*>& buffer_device, DT_* r, cusparseDnVecDescr_t dr, const DT_* x, cusparseDnVecDescr_t dx,
953 const Gate_& gate, cusparseOperation_t op, cudaDataType_t ct, const CuMatDesc& mat_desc, const CSRHelper::CRSMat<DT_, IT_>& mat, DT_ alpha, DT_ beta, cudaStream_t main_stream, const std::array<cudaStream_t, st_>& streams)
954 {
955 // cusparseStatus_t cu_status = cusparseDnVecSetValues(dx, (void*)x);
956 // if (cu_status != CUSPARSE_STATUS_SUCCESS)
957 // throw InternalError(__func__, __FILE__, __LINE__, "cuda error: " + stringify(cusparseGetErrorString(cu_status)));
958 // cu_status = cusparseDnVecSetValues(dr, (void*)r);
959 // if (cu_status != CUSPARSE_STATUS_SUCCESS)
960 // throw InternalError(__func__, __FILE__, __LINE__, "cuda error: " + stringify(cusparseGetErrorString(cu_status)));
961 // call standard apply
962 // cudaMemset(r, 0, mat.num_rows * sizeof(DT_));
963 _apply_mat(buffer_host, buffer_device, r, dr, x, dx, gate, op, ct, mat_desc, mat, alpha, beta, main_stream, streams);
964 // cudaDeviceSynchronize();
965 // cudaCheckLastErr()
966 // if(i == 0)
967 // {
968 // String mt;
969 // for(Index k = 0; k < rows; ++k)
970 // {
971 // mt += stringify(r[k]) + " ";
972 // }
973 // std::cout << "Rank " << comm.rank() << " :" << mt << "\n-------------\n";
974 // }
975
976 // and now scale with vector
977 Memory::TypedView<DT_> freqs_view(gate.get_freqs().elements_view_r(Memory::Location::cuda));
978 const DT_* freqs = freqs_view.get_r();
979 Intern::scale_vec(r, r, freqs, mat.num_rows);
980 }
981
982
983
984 template<typename DT_, typename IT_>
985 FEAT::Solver::Status cuda_apply_amavanka_gmres_parallel(Memory::Arbiter& vec_sol_arb, const Memory::Arbiter& vec_rhs_arb, const CSRHelper::GMRESApplyInfo<DT_, IT_>& apply_info, CSRHelper::GMRESStatus<DT_>& status)
986 {
987 XASSERTM(apply_info.gate, "Requires allocated gate");
988 using namespace FEAT;
989 const auto id_setup = Util::cuda_start_range("GMRES Setup");
990 // extract info
991 const Index rows = apply_info.size;
992 const Index columns = apply_info.size;
993
994 // --- acquire device (cuda) views for all arbiter-backed data; kept alive for the whole solve ---
995 Memory::TypedView<DT_> vec_sol_view(vec_sol_arb.view(Memory::Location::cuda, Memory::Access::read_write));
996 DT_* vec_sol = vec_sol_view.get_w();
997 Memory::TypedView<DT_> vec_rhs_view(vec_rhs_arb.view(Memory::Location::cuda, Memory::Access::read));
998 const DT_* vec_rhs = vec_rhs_view.get_r();
999
1000 Memory::View sys_val_view(apply_info.mat_sys.val->view(Memory::Location::cuda, Memory::Access::read));
1001 Memory::View sys_row_view(apply_info.mat_sys.row->view(Memory::Location::cuda, Memory::Access::read));
1002 Memory::View sys_col_view(apply_info.mat_sys.col->view(Memory::Location::cuda, Memory::Access::read));
1003 Memory::View vanka_val_view(apply_info.mat_vanka.val->view(Memory::Location::cuda, Memory::Access::read));
1004 Memory::View vanka_row_view(apply_info.mat_vanka.row->view(Memory::Location::cuda, Memory::Access::read));
1005 Memory::View vanka_col_view(apply_info.mat_vanka.col->view(Memory::Location::cuda, Memory::Access::read));
1006
1007 const std::vector<Memory::Arbiter*>& vec_v_arbs = *apply_info.vec_v;
1008 std::vector<Memory::TypedView<DT_>> vec_v_views;
1009 vec_v_views.reserve(vec_v_arbs.size());
1010 std::vector<DT_*> vec_v_host(vec_v_arbs.size());
1011 for(std::size_t k = 0; k < vec_v_arbs.size(); ++k)
1012 {
1013 vec_v_views.emplace_back(vec_v_arbs[k]->view(Memory::Location::cuda, Memory::Access::read_write));
1014 vec_v_host[k] = vec_v_views[k].get_w();
1015 }
1016 // const Index used_elements_def = Index(apply_info.mat_sys.row[rows]);
1017 // const Index used_elements_vanka = Index(apply_info.mat_vanka.row[rows]);
1018 // create necessary data arrays on host and device
1019 // setup workspace for cusparse matrices
1020 cusparseOperation_t trans = CUSPARSE_OPERATION_NON_TRANSPOSE;
1021 cudaDataType dt;
1022 cudaDataType ct; //compute type
1023 if (typeid(DT_) == typeid(double))
1024 {
1025 dt = CUDA_R_64F;
1026 ct = CUDA_R_64F;
1027 }
1028 else if (typeid(DT_) == typeid(float))
1029 {
1030 dt = CUDA_R_32F;
1031 ct = CUDA_R_32F;
1032 }
1033 cusparseIndexType_t it;
1034 if(sizeof(IT_) == 4u)
1035 it = CUSPARSE_INDEX_32I;
1036 else if(sizeof(IT_) == 8u)
1037 it = CUSPARSE_INDEX_64I;
1038 cusparseStatus_t cu_status;
1039 const DT_ defect_alpha = DT_(-1);
1040 const DT_ defect_beta = DT_(1);
1041 const DT_ vanka_alpha = DT_(1);
1042 const DT_ vanka_beta = DT_(0);
1043 const DT_ abs_tol = apply_info.abs_tol;
1044 const DT_ rel_tol = apply_info.rel_tol;
1045 const DT_ inner_res_scale = apply_info.res_scale;
1046 const Index krylov_dim = apply_info.krylov_dim;
1047 const Index max_iter = apply_info.max_iter;
1048 const Index min_iter = apply_info.min_iter;
1049
1050 const Index plot_interval = apply_info.plot_interval;
1051 const Solver::PlotMode plot_mode = apply_info.plot_mode;
1052 const auto& gate = *apply_info.gate;
1053 const auto& comm = *gate.get_comm();
1054 const auto& ranks = gate.get_ranks();
1055 const auto& mirrors = gate.get_mirrors();
1056 Memory::TypedView<DT_> freqs_view(gate.get_freqs().elements_view_r(Memory::Location::cuda));
1057 const DT_* const freqs = freqs_view.get_r();
1058 const bool use_multiple_streams = true;
1059
1060 // allocate buffers for our synchoperations
1061 std::vector<DT_*> mirror_buffer_h;
1062 std::vector<DT_*> mirror_buffer_d;
1063
1064 _setup_comm_buffer(mirror_buffer_h, mirror_buffer_d, mirrors);
1065
1066 // our "main" execution stream
1067 cudaStream_t mainstream = 0;
1068 if(use_multiple_streams)
1069 cudaCheck(cudaStreamCreate(&mainstream), "cudaStreamCreate");
1070 // else
1071 // mainstream = 0;
1072 // we need some streams (for now lets do 4)
1073 std::array<cudaStream_t, 4> worker_streams = {mainstream, mainstream, mainstream, mainstream};
1074 for(auto& s : worker_streams)
1075 {
1076 if(use_multiple_streams)
1077 cudaCheck(cudaStreamCreate(&s), "cudasStreamCreatre");
1078 }
1079
1080 // for cusparse, we always use our mainstream
1081 cusparseSetStream(Util::Intern::cusparse_handle, mainstream);
1082
1083
1084 cusparseDnVecDescr_t dx;
1085 {
1086 cu_status = cusparseCreateDnVec(&dx, columns, (void*)vec_sol, dt);
1087 if (cu_status != CUSPARSE_STATUS_SUCCESS)
1088 throw InternalError(__func__, __FILE__, __LINE__, "cuda error: " + stringify(cusparseGetErrorString(cu_status)));
1089 }
1090
1091 cusparseDnVecDescr_t dr;
1092 {
1093 cu_status = cusparseCreateDnVec(&dr, columns, (void*)vec_rhs, dt);
1094 if (cu_status != CUSPARSE_STATUS_SUCCESS)
1095 throw InternalError(__func__, __FILE__, __LINE__, "cuda error: " + stringify(cusparseGetErrorString(cu_status)));
1096 }
1097
1098 CuMatDesc cumat_sys;
1099 Intern::alloc_cusparse_interface<DT_, IT_>(trans, dt, ct, it, dx, dr, sys_row_view.raw_r(), sys_col_view.raw_r(), sys_val_view.raw_r(),
1100 apply_info.mat_sys.num_rows, apply_info.mat_sys.num_cols, apply_info.mat_sys.num_nnz, cumat_sys, defect_alpha, defect_beta);
1101
1102 CuMatDesc cumat_vanka;
1103 Intern::alloc_cusparse_interface<DT_, IT_>(trans, dt, ct, it, dx, dr, vanka_row_view.raw_r(), vanka_col_view.raw_r(), vanka_val_view.raw_r(),
1104 apply_info.mat_vanka.num_rows, apply_info.mat_vanka.num_cols, apply_info.mat_vanka.num_nnz, cumat_vanka, vanka_alpha, vanka_beta);
1105
1106 // allocations for helper arrays
1107 const Index gauss_size = krylov_dim * (krylov_dim+1u) / 2u;
1108 DT_ *_c, *_s, *_q, *_h;
1109 _c = new DT_[size_t(krylov_dim)];
1110 _s = new DT_[size_t(krylov_dim)];
1111 // cudaCheck(cudaMallocHost(&_c, size_t(krylov_dim)*sizeof(DT_)), "cudaMallocHost");
1112 // cudaCheck(cudaMallocHost(&_s, size_t(krylov_dim)*sizeof(DT_)), "cudaMallocHost");
1113 cudaCheck(cudaMallocHost(&_q, size_t(krylov_dim+1)*sizeof(DT_)), "cudaMallocHost");
1114 cudaCheck(cudaMallocHost(&_h, size_t(gauss_size)*sizeof(DT_)), "cudaMallocHost");
1115 // DT_ *_c_d, *_s_d, *_q_d, *_h_d;
1116 DT_ *_q_d, *_h_d;
1117 // cudaCheck(cudaMalloc(&_c_d, size_t(krylov_dim)*sizeof(DT_)), "cudaMalloc");
1118 // cudaCheck(cudaMalloc(&_s_d, size_t(krylov_dim)*sizeof(DT_)), "cudaMalloc");
1119 cudaCheck(cudaMalloc(&_q_d, size_t(krylov_dim+1)*sizeof(DT_)), "cudaMalloc");
1120 cudaCheck(cudaMalloc(&_h_d, size_t(gauss_size)*sizeof(DT_)), "cudaMalloc");
1121 DT_** vec_v = vec_v_host.data();
1122 Memory::TypedView<DT_> vec_w_view(apply_info.vec_w->view(Memory::Location::cuda, Memory::Access::read_write));
1123 DT_* vec_w = vec_w_view.get_w();
1124 DT_** vec_v_d;
1125 cudaCheck(cudaMalloc(&vec_v_d, size_t(krylov_dim+1)*sizeof(DT_*)), "cudaMalloc");
1126
1127 DT_* dot_helper, *dot_helper_d;
1128 cudaCheck(cudaMallocHost(&dot_helper, sizeof(DT_)), "cudaMallocHost");
1129 cudaCheck(cudaMalloc(&dot_helper_d, sizeof(DT_)), "cudaMalloc");
1130
1131 // scratch for the batched projection dots plus the appended self-dot (krylov_dim projections + 1)
1132 DT_ *batch_dots_h, *batch_dots_d;
1133 cudaCheck(cudaMallocHost(&batch_dots_h, size_t(krylov_dim+1)*sizeof(DT_)), "cudaMallocHost");
1134 cudaCheck(cudaMalloc(&batch_dots_d, size_t(krylov_dim+1)*sizeof(DT_)), "cudaMalloc");
1135
1136 if(apply_info.prefetch_data)
1137 {
1138 cudaMemLocation location;
1139 {location.type = cudaMemLocationTypeDevice; location.id = FEAT::Util::cuda_get_device_id();}
1140 // hint to prefetch vector data, if possible
1141 for(Index k = 0; k < krylov_dim+1; ++k)
1142 {
1143 cudaMemPrefetchAsync(vec_v[k], rows*sizeof(DT_), location, 0);
1144 }
1145 }
1146
1147 // cudaCheck(cudaMemsetAsync(_c_d, 0, size_t(krylov_dim)*sizeof(DT_)), "memsetAsync");
1148 // cudaCheck(cudaMemsetAsync(_s_d, 0, size_t(krylov_dim)*sizeof(DT_)), "memsetAsync");
1149 cudaCheck(cudaMemsetAsync(_q_d, 0, size_t(krylov_dim+1)*sizeof(DT_)), "memsetAsync");
1150
1151 cudaCheck(cudaMemcpyAsync(vec_v_d, vec_v, size_t(krylov_dim+1)*sizeof(DT_*), cudaMemcpyHostToDevice), "memcopyAsync");
1152
1153 std::uninitialized_fill(_c, _c+krylov_dim, DT_(0));
1154 std::uninitialized_fill(_s, _s+krylov_dim, DT_(0));
1155 std::uninitialized_fill(_q, _q+krylov_dim+1u, DT_(0));
1156 std::uninitialized_fill(_h, _h+gauss_size, DT_(0));
1157
1158 cudaDeviceSynchronize();
1159 Util::cuda_check_last_error();
1160
1161 // initialize defect
1162 DT_ def_init = DT_(0);
1163 DT_ def_prev = DT_(0);
1164 DT_ def_cur = DT_(0);
1165
1166
1167 // calculate norm
1168 {
1169 auto id_dot = Util::cuda_start_range("Single Dot");
1170 // finally evaluate our defect
1171 Intern::cuda_sync_dot(dot_helper, dot_helper_d, vec_v[0], vec_v[0], freqs, rows, comm, mainstream);
1172 Util::cuda_stop_range(id_dot);
1173 }
1174
1175 def_init = Math::sqrt(*dot_helper);
1176 status.def_init = def_init;
1177
1178
1179 def_prev = def_cur = def_init;
1180
1181 status.def_norm = def_cur;
1182 status.num_iter = 0u;
1183 FEAT::Solver::Status solver_status = FEAT::Solver::Status::progress;
1184
1185 Memory::TypedView<IT_> filter_idx_view(apply_info.def_filter.ind->view(Memory::Location::cuda, Memory::Access::read));
1186 const IT_* filter_idx = filter_idx_view.get_r();
1187 const Index filter_ue = apply_info.def_filter.used_elements;
1188 const Index blocksize = Util::cuda_blocksize_misc;
1189 const Index filter_gridsize = Index(ceil((filter_ue)/(double)(blocksize)));
1190
1191
1192 if(!Math::isfinite(def_init))
1193 solver_status = FEAT::Solver::Status::aborted;
1194
1195 Util::cuda_stop_range(id_setup);
1196
1197 const auto id_outer = Util::cuda_start_range("GMRES Outer Loop");
1198 while(solver_status == FEAT::Solver::Status::progress)
1199 {
1200 // reset h device
1201 cudaCheck(cudaMemsetAsync(_h_d, 0, size_t(gauss_size)*sizeof(DT_)), "memsetAsync");
1202 // set first _q
1203 _q[0] = def_cur;
1204 // cudaCheck(cudaMemcpyAsync(_q_d, _q, sizeof(DT_), cudaMemcpyHostToDevice), "cudaMemcopyAsync");
1205 // normalize v[0]
1206 Intern::cublas_scale(vec_v[0], DT_(1)/_q[0], rows, dt);
1207 // reset h
1208 std::fill(_h, _h+gauss_size, DT_(0));
1209
1210 const auto id_inner = Util::cuda_start_range("Inner GMRES Loop");
1211 Index i(0);
1212 Index h_offset(0);
1213 while(i < krylov_dim)
1214 {
1215 // cudaDeviceSynchronize();
1216 // cudaCheckLastErr()
1217 // if(i == 0)
1218 // {
1219 // String mt;
1220 // for(Index k = 0; k < rows; ++k)
1221 // {
1222 // mt += stringify(vec_v[0][k]) + " ";
1223 // }
1224 // std::cout << "Rank " << comm.rank() << " :" << mt << "\n-------------\n";
1225 // }
1226 const auto first_section = Util::cuda_start_range("First Section");
1227 // apply vanka matrix
1228 {
1229 auto id_vanka = Util::cuda_start_range("Vanka Apply");
1230 _apply_mat_mean(mirror_buffer_h, mirror_buffer_d, vec_w, dr, vec_v[i], dx, gate, trans, ct, cumat_vanka, apply_info.mat_vanka, vanka_alpha, vanka_beta, mainstream, worker_streams);
1231 // and filter
1232 Intern::apply_def_filter(vec_w, filter_idx, filter_ue, blocksize, filter_gridsize);
1233 Util::cuda_stop_range(id_vanka);
1234 }
1235 // cudaDeviceSynchronize();
1236 // cudaCheckLastErr()
1237 // if(i == 0)
1238 // {
1239 // String mt;
1240 // for(Index k = 0; k < rows; ++k)
1241 // {
1242 // mt += stringify(vec_w[k]) + " ";
1243 // }
1244 // std::cout << "Rank " << comm.rank() << " :" << mt << "\n-------------\n";
1245 // }
1246
1247 // calculate defect
1248 {
1249 auto id_defect = Util::cuda_start_range("Defect Calc");
1250 // reuse dr
1251 // cudaMemset(vec_v[i+1], 0, rows * sizeof(DT_));
1252 _apply_mat(mirror_buffer_h, mirror_buffer_d, vec_v[i+1], dr, vec_w, dx, gate, trans, ct, cumat_sys, apply_info.mat_sys, DT_(1), DT_(0), mainstream, worker_streams);
1253 Intern::apply_def_filter(vec_v[i+1], filter_idx, filter_ue, blocksize, filter_gridsize);
1254 Util::cuda_stop_range(id_defect);
1255 }
1256
1257 // fused batched Gram-Schmidt (classical / conditional CGS2): i+1 frequency-weighted
1258 // projections plus the appended self-dot, reduced in a SINGLE all-reduce over i+2 entries
1259 // (previously the norm needed a second all-reduce per inner step)
1260 DT_ alpha = DT_(0);
1261 {
1262 auto id_batched = Util::cuda_start_range("Batched Dot");
1263 Intern::calculate_synced_batched_dots(batch_dots_h, batch_dots_d, vec_v[i+1], vec_v_d, freqs, rows, i+2, comm, mainstream);
1264 // copy the leading i+1 (synchronized) projections back to device for the batched axpy
1265 cudaCheck(cudaMemcpyAsync(batch_dots_d, batch_dots_h, size_t(i+1)*sizeof(DT_), cudaMemcpyHostToDevice, mainstream), "cudaMemcpyAsync");
1266 cudaStreamSynchronize(mainstream);
1267 Util::cuda_stop_range(id_batched);
1268 Intern::add_vecs(vec_v[i+1], vec_v_d, batch_dots_d, rows, i+1, DT_(-1));
1269
1270 // store projections into the Hessenberg column and recover the norm algebraically
1271 DT_ sum_sqr = DT_(0);
1272 for(Index k = 0; k < i+1; ++k)
1273 {
1274 _h[h_offset + k] = batch_dots_h[k];
1275 sum_sqr += Math::sqr(batch_dots_h[k]);
1276 }
1277 const DT_ self_dot = batch_dots_h[i+1];
1278 DT_ nrm_sqr = self_dot - sum_sqr;
1279
1280 // conditional corrective reorthogonalization (cgs2); the second batched all-reduce supplies
1281 // both the corrections and the updated self-dot, so no extra reduction is needed
1282 if((apply_info.ortho_type == FEAT::Solver::KrylovOrthogonalizerType::cgs2)
1283 && (apply_info.force_reortho || (nrm_sqr < Math::sqr(apply_info.reortho_tol) * self_dot)))
1284 {
1285 Intern::calculate_synced_batched_dots(batch_dots_h, batch_dots_d, vec_v[i+1], vec_v_d, freqs, rows, i+2, comm, mainstream);
1286 cudaCheck(cudaMemcpyAsync(batch_dots_d, batch_dots_h, size_t(i+1)*sizeof(DT_), cudaMemcpyHostToDevice, mainstream), "cudaMemcpyAsync");
1287 cudaStreamSynchronize(mainstream);
1288 Intern::add_vecs(vec_v[i+1], vec_v_d, batch_dots_d, rows, i+1, DT_(-1));
1289 DT_ sum_sqr2 = DT_(0);
1290 for(Index k = 0; k < i+1; ++k)
1291 {
1292 _h[h_offset + k] += batch_dots_h[k];
1293 sum_sqr2 += Math::sqr(batch_dots_h[k]);
1294 }
1295 nrm_sqr = batch_dots_h[i+1] - sum_sqr2;
1296 }
1297
1298 // recover the norm; fall back to an explicit synced dot on heavy cancellation (guarantees
1299 // a positive result so the subsequent normalization cannot produce a NaN)
1300 if(nrm_sqr <= Math::Limits<DT_>::epsilon() * DT_(100))
1301 {
1302 auto id_dot = Util::cuda_start_range("Single Dot");
1303 Intern::cuda_sync_dot(dot_helper, dot_helper_d, vec_v[i+1], vec_v[i+1], freqs, rows, comm, mainstream);
1304 Util::cuda_stop_range(id_dot);
1305 nrm_sqr = Math::abs(*dot_helper);
1306 }
1307 alpha = Math::sqrt(nrm_sqr);
1308 }
1309 Util::cuda_stop_range(first_section);
1310 { // open "Second Section" scope; RAII so the convergence/max-iter break below still closes it
1311 FEAT::Util::ScopedNvtxRange _second_section("Second Section");
1312 Intern::cublas_scale(vec_v[i+1], DT_(1)/alpha, rows, dt);
1313 {
1314 const auto id_givens = Util::cuda_start_range("Givens Rotation");
1315 // apply Givens rotations
1316 for(Index k(0); k < i; ++k)
1317 {
1318 DT_* h_i = _h + h_offset;
1319 const DT_ t(h_i[k]);
1320 h_i[k] = _c[k] * t + _s[k] * h_i[k+1];
1321 h_i[k+1] = _s[k] * t - _c[k] * h_i[k+1];
1322 }
1323 Util::cuda_stop_range(id_givens);
1324 }
1325
1326 const auto id_def_push = Util::cuda_start_range("Push defect");
1327 // compute beta
1328 const DT_ beta = Math::sqrt(Math::sqr(_h[h_offset+i]) + Math::sqr(alpha));
1329
1330 // compute next plane rotation
1331 _s[i] = alpha / beta;
1332 _c[i] = _h[h_offset+i] / beta;
1333
1334 // important: back sync h -> h device not required
1335 _h[h_offset+i] = beta;
1336 _q[i+1] = _s[i] * _q[i];
1337 _q[i] *= _c[i];
1338 h_offset += i+1;
1339
1340 Util::cuda_stop_range(id_def_push);
1341 // push our new defect
1342 if(++i < krylov_dim)
1343 {
1344 // get the absolute defect
1345 def_cur = Math::abs(_q[i]);
1346
1347 // // did we diverge?
1348 // if((def_cur > div_abs) || (def_cur > (div_rel * def_init)))
1349 // break;
1350
1351 // minimum number of iterations performed?
1352 if(!(status.num_iter < min_iter))
1353 {
1354 // did we converge?
1355 if((def_cur <= inner_res_scale * abs_tol) && ((def_cur <= inner_res_scale * (rel_tol * def_init))))
1356 break;
1357
1358 // maximum number of iterations performed?
1359 if(status.num_iter >= max_iter)
1360 break;
1361 }
1362
1363 ++status.num_iter;
1364 status.def_norm = def_cur;
1365 // plot?
1366 if((plot_mode == Solver::PlotMode::iter || plot_mode == Solver::PlotMode::all) && status.num_iter%plot_interval == 0u)
1367 {
1368 FEAT::String msg = FEAT::String("CudaGMRES")
1369 + "* " + stringify(status.num_iter).pad_front(4)
1370 + " : " + stringify_fp_sci(def_cur);
1371 comm.print(msg);
1372 }
1373 }
1374
1375 } // close "Second Section" scope (RAII)
1376 }
1377 Util::cuda_stop_range(id_inner);
1378
1379 const auto id_update = Util::cuda_start_range("Update Solution");
1380 {
1381 const Index n = Math::min(i, krylov_dim);
1382 const auto id_h_solve = Util::cuda_start_range("Solve Hessenberg");
1383 // solve H*q = q
1384 for(Index k(n); k > 0;)
1385 {
1386 --k;
1387 const Index h_offset = (k+1)*k/2u;
1388 _q[k] /= _h[h_offset + k];
1389 for(Index j(k); j > 0;)
1390 {
1391 --j;
1392 _q[j] -= _h[h_offset + j] * _q[k];
1393 }
1394 }
1395 Util::cuda_stop_range(id_h_solve);
1396 // copy _q values
1397 cudaCheck(cudaMemcpyAsync(_q_d, _q, size_t(n)*sizeof(DT_), cudaMemcpyHostToDevice), "cudaMemcpyAsync");
1398
1399 // Runtime::SyncGuard sync_guard;
1400 // update solution
1401 cudaCheck(cudaMemsetAsync(vec_w, 0, rows*sizeof(DT_)), "cudaMemcpyAsync");
1402 Intern::add_vecs(vec_w, vec_v_d, _q_d, rows, n, DT_(1));
1403
1404 // apply vanka matrix
1405 {
1406 _apply_mat_mean(mirror_buffer_h, mirror_buffer_d, vec_v[0], dr, vec_w, dx, gate, trans, ct, cumat_vanka, apply_info.mat_vanka, vanka_alpha, vanka_beta, mainstream, worker_streams);
1407 Intern::apply_def_filter(vec_v[0], filter_idx, filter_ue, blocksize, filter_gridsize);
1408 }
1409 //update solution
1410 Intern::cublas_axpy(vec_sol, DT_(1), vec_v[0], rows, dt);
1411
1412 // compute real residual
1413 {
1414 _apply_mat(mirror_buffer_h, mirror_buffer_d, vec_v[0], dr, vec_sol, dx, vec_rhs, gate, trans, ct, cumat_sys, apply_info.mat_sys, defect_alpha, defect_beta, mainstream, worker_streams);
1415 Intern::apply_def_filter(vec_v[0], filter_idx, filter_ue, blocksize, filter_gridsize);
1416 }
1417
1418 // increase iteration count
1419 ++status.num_iter;
1420
1421 def_prev = def_cur;
1422
1423 {
1424 auto id_dot = Util::cuda_start_range("Single Dot");
1425 // finally evaluate our defect
1426 Intern::cuda_sync_dot(dot_helper, dot_helper_d, vec_v[0], vec_v[0], freqs, rows, comm, mainstream);
1427 Util::cuda_stop_range(id_dot);
1428 }
1429
1430 def_cur = Math::sqrt(*dot_helper);
1431 status.def_norm = def_cur;
1432
1433 solver_status = _analyze_defect(status, def_prev, def_init, max_iter, min_iter, abs_tol, rel_tol);
1434 }
1435 Util::cuda_stop_range(id_update);
1436 }
1437 Util::cuda_stop_range(id_outer);
1438
1439
1440
1441 // cudaCheck(cudaFreeHost(_c), "cudaFreeHost");
1442 // cudaCheck(cudaFreeHost(_s), "cudaFreeHost");
1443 delete[](_c);
1444 delete[](_s);
1445 cudaCheck(cudaFreeHost(dot_helper), "cudaFreeHost");
1446 cudaCheck(cudaFreeHost(batch_dots_h), "cudaFreeHost");
1447 cudaCheck(cudaFree(batch_dots_d), "cudaFree");
1448 cudaCheck(cudaFreeHost(_q), "cudaFreeHost");
1449 cudaCheck(cudaFreeHost(_h), "cudaFreeHost");
1450 // cudaCheck(cudaFree(_c_d), "cudaFree");
1451 // cudaCheck(cudaFree(_s_d), "cudaFree");
1452 cudaCheck(cudaFree(_q_d), "cudaFree");
1453 cudaCheck(cudaFree(_h_d), "cudaFree");
1454 cudaCheck(cudaFree(vec_v_d), "cudaFree");
1455 cudaCheck(cudaFree(dot_helper_d), "cudaFree");
1456
1457
1458 // free buffer
1459 for(auto k : mirror_buffer_h)
1460 {
1461 cudaCheck(cudaFreeHost(k), "cudaFreeHost");
1462 }
1463 mirror_buffer_h.clear();
1464 for(auto k : mirror_buffer_d)
1465 {
1466 cudaCheck(cudaFree(k), "cudaFree");
1467 }
1468 mirror_buffer_d.clear();
1469
1470
1471
1472
1473
1474 Intern::cumat_free(cumat_sys);
1475 Intern::cumat_free(cumat_vanka);
1476 cusparseDestroyDnVec(dx);
1477 cusparseDestroyDnVec(dr);
1478
1479 // reset cusparse context
1480 cusparseSetStream(Util::Intern::cusparse_handle, 0);
1481
1482 if(use_multiple_streams)
1483 {
1484 // destroy streams
1485 for(auto& s : worker_streams)
1486 {
1487 cudaCheck(cudaStreamDestroy(s), "cudasStreamDestroy");
1488 }
1489 cudaCheck(cudaStreamDestroy(mainstream), "cudasStreamDestroy");
1490 }
1491
1492
1493
1494 return solver_status;
1495 }
1496}
1497
1498template FEAT::Solver::Status FEAT::Solver::VankaGMRES::cuda_apply_amavanka_gmres_seq<double, std::uint32_t>(FEAT::Memory::Arbiter&, const FEAT::Memory::Arbiter&, const FEAT::Solver::CSRHelper::GMRESApplyInfo<double, std::uint32_t>&, FEAT::Solver::CSRHelper::GMRESStatus<double>&);
1499template FEAT::Solver::Status FEAT::Solver::VankaGMRES::cuda_apply_amavanka_gmres_seq<float, std::uint32_t>(FEAT::Memory::Arbiter&, const FEAT::Memory::Arbiter&, const FEAT::Solver::CSRHelper::GMRESApplyInfo<float, std::uint32_t>&, FEAT::Solver::CSRHelper::GMRESStatus<float>&);
1500template FEAT::Solver::Status FEAT::Solver::VankaGMRES::cuda_apply_amavanka_gmres_seq<double, std::uint64_t>(FEAT::Memory::Arbiter&, const FEAT::Memory::Arbiter&, const FEAT::Solver::CSRHelper::GMRESApplyInfo<double, std::uint64_t>&, FEAT::Solver::CSRHelper::GMRESStatus<double>&);
1501template FEAT::Solver::Status FEAT::Solver::VankaGMRES::cuda_apply_amavanka_gmres_seq<float, std::uint64_t>(FEAT::Memory::Arbiter&, const FEAT::Memory::Arbiter&, const FEAT::Solver::CSRHelper::GMRESApplyInfo<float, std::uint64_t>&, FEAT::Solver::CSRHelper::GMRESStatus<float>&);
1502
1503template FEAT::Solver::Status FEAT::Solver::VankaGMRES::cuda_apply_amavanka_gmres_parallel<double, std::uint32_t>(FEAT::Memory::Arbiter&, const FEAT::Memory::Arbiter&, const FEAT::Solver::CSRHelper::GMRESApplyInfo<double, std::uint32_t>&, FEAT::Solver::CSRHelper::GMRESStatus<double>&);
1504template FEAT::Solver::Status FEAT::Solver::VankaGMRES::cuda_apply_amavanka_gmres_parallel<float, std::uint32_t>(FEAT::Memory::Arbiter&, const FEAT::Memory::Arbiter&, const FEAT::Solver::CSRHelper::GMRESApplyInfo<float, std::uint32_t>&, FEAT::Solver::CSRHelper::GMRESStatus<float>&);
1505template FEAT::Solver::Status FEAT::Solver::VankaGMRES::cuda_apply_amavanka_gmres_parallel<double, std::uint64_t>(FEAT::Memory::Arbiter&, const FEAT::Memory::Arbiter&, const FEAT::Solver::CSRHelper::GMRESApplyInfo<double, std::uint64_t>&, FEAT::Solver::CSRHelper::GMRESStatus<double>&);
1506template FEAT::Solver::Status FEAT::Solver::VankaGMRES::cuda_apply_amavanka_gmres_parallel<float, std::uint64_t>(FEAT::Memory::Arbiter&, const FEAT::Memory::Arbiter&, const FEAT::Solver::CSRHelper::GMRESApplyInfo<float, std::uint64_t>&, FEAT::Solver::CSRHelper::GMRESStatus<float>&);