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"
17#include <kernel/util/cuda_helper.cuh>
20namespace FEAT::Solver::VankaGMRES
23 namespace cg = cooperative_groups;
27 cusparseSpMatDescr_t descr=0;
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)
42 const auto algo = CUSPARSE_SPMV_CSR_ALG1;
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)));
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)));
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)));
60 static void cumat_free(CuMatDesc& mat_desc)
62 Memory::free_cuda(mat_desc.buffer);
63 mat_desc.buffer = nullptr;
64 cusparseDestroySpMat(mat_desc.descr);
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)
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)));
76 template<typename DT_>
77 static void cublas_dot(DT_& result, const DT_* x, const DT_* y, Index size, cudaDataType_t dt)
79 cublasStatus_t status;
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)));
87 template<typename DT_>
88 static void cublas_scale(DT_* x, DT_ a, Index size, cudaDataType_t dt)
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)));
95 template<typename DT_>
96 static void cublas_axpy(DT_* r, DT_ a, const DT_* x, Index size, cudaDataType_t dt)
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)));
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)
106 cudaCheck(cudaMemsetAsync(device_helper, 0, sizeof(DT_)), "cudaMemSetAsync");
107 constexpr Index blocksize = 512u;
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);
118 template <typename DT_, typename IT_>
119 __global__ void cuda_unit_filter_def(DT_ * v, const IT_ * sv_indices, const Index ue)
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)
125 v[sv_indices[i]] = DT_(0);
129 template <typename DT_>
130 __global__ void cuda_ComponentProduct(DT_ * r, const DT_ * x, const DT_ * y, const Index count)
132 Index idx = threadIdx.x + blockDim.x * blockIdx.x;
133 for(Index i = idx; i < count; i += Index(blockDim.x*gridDim.x))
138 * \brief Performs m[k] = alpha * (A*rhs)[k_j] + beta * m[k]
139 * where k_j is the actual sparse mirror index
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)
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))
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)
152 val += values[k] * rhs[colidx[k]];
154 mirror_buffer[i] = alpha * val + beta * mirror_buffer[i];
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)
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))
165 mirror_buffer[i] = vec[mirror_indx[i]];
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)
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))
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]);
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)
187 block.x = (unsigned)blocksize;
188 grid.x = (unsigned)gridsize;
189 cuda_unit_filter_def<<<grid, block>>>(vec, filter_idx, filter_ue);
193 template<typename DT_>
194 static void scale_vec(DT_* r, const DT_* x, const DT_* y, Index size, cudaStream_t stream = 0)
196 Index blocksize = Util::cuda_blocksize_axpy;
199 block.x = (unsigned)blocksize;
200 // in theory, this should be num_rows
201 grid.x = (unsigned)ceil((size)/(double)(block.x));
203 cuda_ComponentProduct<<<grid, block, 0, stream>>>(r, x, y, size);
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)
210 constexpr Index blocksize = 256u;
211 // constexpr Index blocksize = 32u;
212 constexpr int num_batch = 4;
215 block.x = (unsigned)blocksize;
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);
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)
226 constexpr Index blocksize = 256u;
227 // constexpr Index blocksize = 32u;
228 constexpr int num_batch = 4;
231 block.x = (unsigned)blocksize;
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);
238 cudaCheck(cudaMemcpyAsync(dot_helper, dot_helper_device, size_t(num_dots)*sizeof(DT_), cudaMemcpyDeviceToHost, stream), "cudaMemcpyAsync");
239 cudaStreamSynchronize(stream);
241 comm.allreduce(dot_helper, dot_helper, num_dots, Dist::op_sum);
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)
247 if(vec_size == Index(0))
249 constexpr Index blocksize = 128u;
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);
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)
263 constexpr DT_ tol = DT_(1E-8);
264 Index idx = threadIdx.x + blockDim.x * blockIdx.x;
265 if(idx >= num_mirror)
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]));
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)
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));
288 // for(Index k = 0; k < n; ++k)
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();
303 // cudaDeviceSynchronize();
304 // cudaCheckLastErr()
306 apply_cu_spmv(op, ct, dx, dr, mat_desc, alpha, beta);
308 cudaDeviceSynchronize();
310 for(Index k = 0; k < n; ++k)
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();
325 // cudaDeviceSynchronize();
326 // cudaCheckLastErr()
328 // for(Index k = 0; k < n; ++k)
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)
334 // if(Math::abs(r[mirr_indx[l]] - buffer_host[k][l]) > DT_(1E-3))
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));
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()
349 Dist::RequestVector _send_reqs, _recv_reqs;
351 _recv_reqs.reserve(n);
352 for(std::size_t i(0); i < n; ++i)
355 _recv_reqs.push_back(comm.irecv(buffer_host.at(2u*i+1), mirrors.at(i).num_indices(), ranks.at(i)));
359 _send_reqs.reserve(n);
361 // wait for stream to finish and push send
363 for(std::size_t i(0); i < n; ++i)
365 // wait for stream to finish
366 cudaStreamSynchronize(streams[s_id]);
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();
372 // wait for sync to finish and copy back to device
373 // process all pending receives
375 for(std::size_t idx(0u); _recv_reqs.wait_any(idx); )
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();
382 //wait for all streams to finish
383 cudaDeviceSynchronize();
388 for(Index k = 0; k < n; ++k)
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...
399 // wait for all sends to finish
400 _send_reqs.wait_all();
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)
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;
414 // if(this->is_diverged(def_cur))
415 // return Status::diverged;
417 // maximum number of iterations performed?
418 if(stat.num_iter >= max_iter)
419 return Status::max_iter;
421 // minimum number of iterations performed?
422 if(stat.num_iter < min_iter)
423 return Status::progress;
426 if((stat.def_norm <= tol_abs) && ((stat.def_norm <= (tol_rel * def_init))))
427 return Status::success;
429 // // check for stagnation?
430 // if(check_stag && (this->_min_stag_iter > Index(0)))
432 // // did this iteration stagnate?
433 // if(def_cur >= this->_stag_rate * def_prev)
435 // // increment stagnation count
436 // if(++this->_num_stag_iter >= this->_min_stag_iter)
437 // return Status::stagnated;
441 // // this iteration did not stagnate
442 // this->_num_stag_iter = Index(0);
446 // continue iterating
447 return Status::progress;
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)
453 using namespace FEAT;
454 const auto id_setup = Util::cuda_start_range("GMRES Setup");
456 const Index rows = apply_info.size;
457 const Index columns = apply_info.size;
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();
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));
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)
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();
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;
490 cudaDataType ct; //compute type
491 if (typeid(DT_) == typeid(double))
496 else if (typeid(DT_) == typeid(float))
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;
518 const Index plot_interval = apply_info.plot_interval;
519 const Solver::PlotMode plot_mode = apply_info.plot_mode;
521 cusparseDnVecDescr_t dx;
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)));
528 cusparseDnVecDescr_t dr;
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)));
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);
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);
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;
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();
564 cudaCheck(cudaMalloc(&vec_v_d, size_t(krylov_dim+1)*sizeof(DT_*)), "cudaMalloc");
566 if(apply_info.prefetch_data)
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)
573 cudaMemPrefetchAsync(vec_v[k], rows*sizeof(DT_), location, 0);
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");
581 cudaCheck(cudaMemcpyAsync(vec_v_d, vec_v, size_t(krylov_dim+1)*sizeof(DT_*), cudaMemcpyHostToDevice), "memcopyAsync");
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));
588 cudaDeviceSynchronize();
589 Util::cuda_check_last_error();
592 DT_ def_init = DT_(0);
593 DT_ def_prev = DT_(0);
594 DT_ def_cur = DT_(0);
598 Intern::cublas_dot(def_init, vec_v[0], vec_v[0], rows, dt);
599 cudaDeviceSynchronize();
600 Util::cuda_check_last_error();
602 def_init = Math::sqrt(def_init);
603 status.def_init = def_init;
606 def_prev = def_cur = def_init;
608 status.def_norm = def_cur;
609 status.num_iter = 0u;
610 FEAT::Solver::Status solver_status = FEAT::Solver::Status::progress;
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)));
619 if(!Math::isfinite(def_init))
620 solver_status = FEAT::Solver::Status::aborted;
622 Util::cuda_stop_range(id_setup);
624 const auto id_outer = Util::cuda_start_range("GMRES Outer Loop");
625 while(solver_status == FEAT::Solver::Status::progress)
628 cudaCheck(cudaMemsetAsync(_h_d, 0, size_t(gauss_size)*sizeof(DT_)), "memsetAsync");
631 // cudaCheck(cudaMemcpyAsync(_q_d, _q, sizeof(DT_), cudaMemcpyHostToDevice), "cudaMemcopyAsync");
633 Intern::cublas_scale(vec_v[0], DT_(1)/_q[0], rows, dt);
635 std::fill(_h, _h+gauss_size, DT_(0));
637 const auto id_inner = Util::cuda_start_range("Inner GMRES Loop");
640 while(i < krylov_dim)
642 const auto first_section = Util::cuda_start_range("First Section");
643 // apply vanka matrix
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)));
652 Intern::apply_cu_spmv(trans, ct, dx, dr, cumat_vanka, vanka_alpha, vanka_beta);
654 Intern::apply_def_filter(vec_w, filter_idx, filter_ue, blocksize, filter_gridsize);
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);
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.
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));
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)
685 _h[h_offset + k] = batch_dots_h[k];
686 sum_sqr += Math::sqr(batch_dots_h[k]);
688 const DT_ self_dot = batch_dots_h[i+1];
689 DT_ nrm_sqr = self_dot - sum_sqr;
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)))
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)
705 _h[h_offset + k] += batch_dots_h[k];
706 sum_sqr2 += Math::sqr(batch_dots_h[k]);
708 nrm_sqr = batch_dots_h[i+1] - sum_sqr2;
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))
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);
720 alpha = Math::sqrt(nrm_sqr);
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);
727 const auto id_givens = Util::cuda_start_range("Givens Rotation");
728 // apply Givens rotations
729 for(Index k(0); k < i; ++k)
731 DT_* h_i = _h + h_offset;
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];
736 Util::cuda_stop_range(id_givens);
739 const auto id_def_push = Util::cuda_start_range("Push defect");
741 const DT_ beta = Math::sqrt(Math::sqr(_h[h_offset+i]) + Math::sqr(alpha));
743 // compute next plane rotation
744 _s[i] = alpha / beta;
745 _c[i] = _h[h_offset+i] / beta;
747 // important: back sync h -> h device not required
748 _h[h_offset+i] = beta;
749 _q[i+1] = _s[i] * _q[i];
753 Util::cuda_stop_range(id_def_push);
754 // push our new defect
757 // get the absolute defect
758 def_cur = Math::abs(_q[i]);
760 // // did we diverge?
761 // if((def_cur > div_abs) || (def_cur > (div_rel * def_init)))
764 // minimum number of iterations performed?
765 if(!(status.num_iter < min_iter))
768 if((def_cur <= inner_res_scale * abs_tol) && ((def_cur <= inner_res_scale * (rel_tol * def_init))))
771 // maximum number of iterations performed?
772 if(status.num_iter >= max_iter)
777 status.def_norm = def_cur;
779 if((plot_mode == Solver::PlotMode::iter || plot_mode == Solver::PlotMode::all) && status.num_iter%plot_interval == 0u)
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";
788 } // close "Second Section" scope (RAII)
790 Util::cuda_stop_range(id_inner);
792 const auto id_update = Util::cuda_start_range("Update Solution");
794 const Index n = Math::min(i, krylov_dim);
795 const auto id_h_solve = Util::cuda_start_range("Solve Hessenberg");
797 for(Index k(n); k > 0;)
800 const Index h_offset = (k+1)*k/2u;
801 _q[k] /= _h[h_offset + k];
802 for(Index j(k); j > 0;)
805 _q[j] -= _h[h_offset + j] * _q[k];
808 Util::cuda_stop_range(id_h_solve);
810 cudaCheck(cudaMemcpyAsync(_q_d, _q, size_t(n)*sizeof(DT_), cudaMemcpyHostToDevice), "cudaMemcpyAsync");
812 // Runtime::SyncGuard sync_guard;
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));
818 // apply vanka matrix
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)));
827 Intern::apply_cu_spmv(trans, ct, dx, dr, cumat_vanka, vanka_alpha, vanka_beta);
829 Intern::apply_def_filter(vec_v[0], filter_idx, filter_ue, blocksize, filter_gridsize);
832 Intern::cublas_axpy(vec_sol, DT_(1), vec_v[0], rows, dt);
834 // compute real residual
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)));
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);
844 Intern::apply_def_filter(vec_v[0], filter_idx, filter_ue, blocksize, filter_gridsize);
847 // increase iteration count
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();
857 def_cur = Math::sqrt(def_cur);
858 status.def_norm = def_cur;
860 solver_status = _analyze_defect(status, def_prev, def_init, max_iter, min_iter, abs_tol, rel_tol);
862 Util::cuda_stop_range(id_update);
864 Util::cuda_stop_range(id_outer);
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");
883 Intern::cumat_free(cumat_sys);
884 Intern::cumat_free(cumat_vanka);
885 cusparseDestroyDnVec(dx);
886 cusparseDestroyDnVec(dr);
888 return solver_status;
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)
895 host_buffer.resize(mirrors.size()*2u);
896 device_buffer.resize(mirrors.size());
898 for(Index k = 0; k < mirrors.size(); ++k)
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");
906 for(Index k = 0; k < mirrors.size(); ++k)
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));
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)
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)));
925 Intern::apply_synced_mat(buffer_host, buffer_device, r, dr, x, dx, gate, op, ct, mat_desc, mat, alpha, beta, main_stream, streams);
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)
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)));
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);
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);
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)
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()
969 // for(Index k = 0; k < rows; ++k)
971 // mt += stringify(r[k]) + " ";
973 // std::cout << "Rank " << comm.rank() << " :" << mt << "\n-------------\n";
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);
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)
987 XASSERTM(apply_info.gate, "Requires allocated gate");
988 using namespace FEAT;
989 const auto id_setup = Util::cuda_start_range("GMRES Setup");
991 const Index rows = apply_info.size;
992 const Index columns = apply_info.size;
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();
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));
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)
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();
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;
1022 cudaDataType ct; //compute type
1023 if (typeid(DT_) == typeid(double))
1028 else if (typeid(DT_) == typeid(float))
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;
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;
1060 // allocate buffers for our synchoperations
1061 std::vector<DT_*> mirror_buffer_h;
1062 std::vector<DT_*> mirror_buffer_d;
1064 _setup_comm_buffer(mirror_buffer_h, mirror_buffer_d, mirrors);
1066 // our "main" execution stream
1067 cudaStream_t mainstream = 0;
1068 if(use_multiple_streams)
1069 cudaCheck(cudaStreamCreate(&mainstream), "cudaStreamCreate");
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)
1076 if(use_multiple_streams)
1077 cudaCheck(cudaStreamCreate(&s), "cudasStreamCreatre");
1080 // for cusparse, we always use our mainstream
1081 cusparseSetStream(Util::Intern::cusparse_handle, mainstream);
1084 cusparseDnVecDescr_t dx;
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)));
1091 cusparseDnVecDescr_t dr;
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)));
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);
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);
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;
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();
1125 cudaCheck(cudaMalloc(&vec_v_d, size_t(krylov_dim+1)*sizeof(DT_*)), "cudaMalloc");
1127 DT_* dot_helper, *dot_helper_d;
1128 cudaCheck(cudaMallocHost(&dot_helper, sizeof(DT_)), "cudaMallocHost");
1129 cudaCheck(cudaMalloc(&dot_helper_d, sizeof(DT_)), "cudaMalloc");
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");
1136 if(apply_info.prefetch_data)
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)
1143 cudaMemPrefetchAsync(vec_v[k], rows*sizeof(DT_), location, 0);
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");
1151 cudaCheck(cudaMemcpyAsync(vec_v_d, vec_v, size_t(krylov_dim+1)*sizeof(DT_*), cudaMemcpyHostToDevice), "memcopyAsync");
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));
1158 cudaDeviceSynchronize();
1159 Util::cuda_check_last_error();
1161 // initialize defect
1162 DT_ def_init = DT_(0);
1163 DT_ def_prev = DT_(0);
1164 DT_ def_cur = DT_(0);
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);
1175 def_init = Math::sqrt(*dot_helper);
1176 status.def_init = def_init;
1179 def_prev = def_cur = def_init;
1181 status.def_norm = def_cur;
1182 status.num_iter = 0u;
1183 FEAT::Solver::Status solver_status = FEAT::Solver::Status::progress;
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)));
1192 if(!Math::isfinite(def_init))
1193 solver_status = FEAT::Solver::Status::aborted;
1195 Util::cuda_stop_range(id_setup);
1197 const auto id_outer = Util::cuda_start_range("GMRES Outer Loop");
1198 while(solver_status == FEAT::Solver::Status::progress)
1201 cudaCheck(cudaMemsetAsync(_h_d, 0, size_t(gauss_size)*sizeof(DT_)), "memsetAsync");
1204 // cudaCheck(cudaMemcpyAsync(_q_d, _q, sizeof(DT_), cudaMemcpyHostToDevice), "cudaMemcopyAsync");
1206 Intern::cublas_scale(vec_v[0], DT_(1)/_q[0], rows, dt);
1208 std::fill(_h, _h+gauss_size, DT_(0));
1210 const auto id_inner = Util::cuda_start_range("Inner GMRES Loop");
1213 while(i < krylov_dim)
1215 // cudaDeviceSynchronize();
1216 // cudaCheckLastErr()
1220 // for(Index k = 0; k < rows; ++k)
1222 // mt += stringify(vec_v[0][k]) + " ";
1224 // std::cout << "Rank " << comm.rank() << " :" << mt << "\n-------------\n";
1226 const auto first_section = Util::cuda_start_range("First Section");
1227 // apply vanka matrix
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);
1232 Intern::apply_def_filter(vec_w, filter_idx, filter_ue, blocksize, filter_gridsize);
1233 Util::cuda_stop_range(id_vanka);
1235 // cudaDeviceSynchronize();
1236 // cudaCheckLastErr()
1240 // for(Index k = 0; k < rows; ++k)
1242 // mt += stringify(vec_w[k]) + " ";
1244 // std::cout << "Rank " << comm.rank() << " :" << mt << "\n-------------\n";
1249 auto id_defect = Util::cuda_start_range("Defect Calc");
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);
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)
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));
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)
1274 _h[h_offset + k] = batch_dots_h[k];
1275 sum_sqr += Math::sqr(batch_dots_h[k]);
1277 const DT_ self_dot = batch_dots_h[i+1];
1278 DT_ nrm_sqr = self_dot - sum_sqr;
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)))
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)
1292 _h[h_offset + k] += batch_dots_h[k];
1293 sum_sqr2 += Math::sqr(batch_dots_h[k]);
1295 nrm_sqr = batch_dots_h[i+1] - sum_sqr2;
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))
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);
1307 alpha = Math::sqrt(nrm_sqr);
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);
1314 const auto id_givens = Util::cuda_start_range("Givens Rotation");
1315 // apply Givens rotations
1316 for(Index k(0); k < i; ++k)
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];
1323 Util::cuda_stop_range(id_givens);
1326 const auto id_def_push = Util::cuda_start_range("Push defect");
1328 const DT_ beta = Math::sqrt(Math::sqr(_h[h_offset+i]) + Math::sqr(alpha));
1330 // compute next plane rotation
1331 _s[i] = alpha / beta;
1332 _c[i] = _h[h_offset+i] / beta;
1334 // important: back sync h -> h device not required
1335 _h[h_offset+i] = beta;
1336 _q[i+1] = _s[i] * _q[i];
1340 Util::cuda_stop_range(id_def_push);
1341 // push our new defect
1342 if(++i < krylov_dim)
1344 // get the absolute defect
1345 def_cur = Math::abs(_q[i]);
1347 // // did we diverge?
1348 // if((def_cur > div_abs) || (def_cur > (div_rel * def_init)))
1351 // minimum number of iterations performed?
1352 if(!(status.num_iter < min_iter))
1355 if((def_cur <= inner_res_scale * abs_tol) && ((def_cur <= inner_res_scale * (rel_tol * def_init))))
1358 // maximum number of iterations performed?
1359 if(status.num_iter >= max_iter)
1364 status.def_norm = def_cur;
1366 if((plot_mode == Solver::PlotMode::iter || plot_mode == Solver::PlotMode::all) && status.num_iter%plot_interval == 0u)
1368 FEAT::String msg = FEAT::String("CudaGMRES")
1369 + "* " + stringify(status.num_iter).pad_front(4)
1370 + " : " + stringify_fp_sci(def_cur);
1375 } // close "Second Section" scope (RAII)
1377 Util::cuda_stop_range(id_inner);
1379 const auto id_update = Util::cuda_start_range("Update Solution");
1381 const Index n = Math::min(i, krylov_dim);
1382 const auto id_h_solve = Util::cuda_start_range("Solve Hessenberg");
1384 for(Index k(n); k > 0;)
1387 const Index h_offset = (k+1)*k/2u;
1388 _q[k] /= _h[h_offset + k];
1389 for(Index j(k); j > 0;)
1392 _q[j] -= _h[h_offset + j] * _q[k];
1395 Util::cuda_stop_range(id_h_solve);
1397 cudaCheck(cudaMemcpyAsync(_q_d, _q, size_t(n)*sizeof(DT_), cudaMemcpyHostToDevice), "cudaMemcpyAsync");
1399 // Runtime::SyncGuard sync_guard;
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));
1404 // apply vanka matrix
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);
1410 Intern::cublas_axpy(vec_sol, DT_(1), vec_v[0], rows, dt);
1412 // compute real residual
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);
1418 // increase iteration count
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);
1430 def_cur = Math::sqrt(*dot_helper);
1431 status.def_norm = def_cur;
1433 solver_status = _analyze_defect(status, def_prev, def_init, max_iter, min_iter, abs_tol, rel_tol);
1435 Util::cuda_stop_range(id_update);
1437 Util::cuda_stop_range(id_outer);
1441 // cudaCheck(cudaFreeHost(_c), "cudaFreeHost");
1442 // cudaCheck(cudaFreeHost(_s), "cudaFreeHost");
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");
1459 for(auto k : mirror_buffer_h)
1461 cudaCheck(cudaFreeHost(k), "cudaFreeHost");
1463 mirror_buffer_h.clear();
1464 for(auto k : mirror_buffer_d)
1466 cudaCheck(cudaFree(k), "cudaFree");
1468 mirror_buffer_d.clear();
1474 Intern::cumat_free(cumat_sys);
1475 Intern::cumat_free(cumat_vanka);
1476 cusparseDestroyDnVec(dx);
1477 cusparseDestroyDnVec(dr);
1479 // reset cusparse context
1480 cusparseSetStream(Util::Intern::cusparse_handle, 0);
1482 if(use_multiple_streams)
1485 for(auto& s : worker_streams)
1487 cudaCheck(cudaStreamDestroy(s), "cudasStreamDestroy");
1489 cudaCheck(cudaStreamDestroy(mainstream), "cudasStreamDestroy");
1494 return solver_status;
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>&);
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>&);