1// FEAT3: Finite Element Analysis Toolbox, Version 3
2// Copyright (C) 2010 by Stefan Turek & the FEAT group
3// FEAT3 is released under the GNU General Public License version 3,
4// see the file 'copyright.txt' in the top level directory for details.
6#include <kernel/base_header.hpp>
7#include <kernel/util/memory_aux.hpp>
8#include <kernel/util/memory_arbiter.hpp>
9#include <kernel/util/cuda_util.hpp>
10#include <kernel/util/cuda_helper.cuh>
11#include <kernel/util/dist.hpp>
12#include <kernel/lafem/arch/matvecmult_bcsr_dense.hpp>
13#include <kernel/solver/base.hpp>
14#include <kernel/solver/backend_aux/richardson_apply_helper.hpp>
15#include <kernel/solver/amavanka_richardson.hpp>
22namespace FEAT::Solver::VankaRichardson
26 // ---- small device kernels (grid-stride loops) --------------------------------------------
28 template<typename DT_>
29 __global__ void cuda_axpy(DT_* r, const DT_ alpha, const DT_* x, const Index n)
31 for(Index i = threadIdx.x + blockDim.x * blockIdx.x; i < n; i += Index(blockDim.x * gridDim.x))
35 template<typename DT_, typename IT_>
36 __global__ void cuda_unit_filter_zero(DT_* v, const IT_* idx, const Index ue)
38 for(Index i = threadIdx.x + blockDim.x * blockIdx.x; i < ue; i += Index(blockDim.x * gridDim.x))
42 template<typename DT_>
43 __global__ void cuda_comp_prod(DT_* v, const DT_* f, const Index n)
45 for(Index i = threadIdx.x + blockDim.x * blockIdx.x; i < n; i += Index(blockDim.x * gridDim.x))
49 /// blocked/scalar mirror gather: buf[i*bs + d] = v[idx[i]*bs + d]
50 template<typename DT_, typename IT_>
51 __global__ void cuda_gather(DT_* __restrict__ buf, const IT_* __restrict__ idx, const Index n_nodes, const DT_* __restrict__ v, const int bs)
53 const Index total = n_nodes * Index(bs);
54 for(Index t = threadIdx.x + blockDim.x * blockIdx.x; t < total; t += Index(blockDim.x * gridDim.x))
56 const Index i = t / Index(bs);
57 const Index d = t % Index(bs);
58 buf[t] = v[Index(idx[i]) * Index(bs) + d];
62 /// blocked/scalar mirror scatter-add (atomic, allows asynchronous merge): v[idx[i]*bs + d] += buf[i*bs + d]
63 template<typename DT_, typename IT_>
64 __global__ void cuda_scatter_add(DT_* __restrict__ v, const DT_* __restrict__ buf, const IT_* __restrict__ idx, const Index n_nodes, const int bs)
66 const Index total = n_nodes * Index(bs);
67 for(Index t = threadIdx.x + blockDim.x * blockIdx.x; t < total; t += Index(blockDim.x * gridDim.x))
69 const Index i = t / Index(bs);
70 const Index d = t % Index(bs);
71 cuda::atomic_ref<DT_, cuda::thread_scope_device> ref(v[Index(idx[i]) * Index(bs) + d]);
72 ref.fetch_add(buf[t]);
76 // ---- launch helpers ----------------------------------------------------------------------
78 static inline dim3 grid_for(Index n, unsigned block)
80 return dim3((unsigned)((n + Index(block) - 1u) / Index(block)));
83 template<typename DT_>
84 static void launch_axpy(DT_* r, DT_ alpha, const DT_* x, Index n, cudaStream_t s = 0)
86 if(n == Index(0)) return;
87 const unsigned bs = 256u;
88 cuda_axpy<DT_><<<grid_for(n, bs), bs, 0, s>>>(r, alpha, x, n);
92 template<typename DT_, typename IT_>
93 static void launch_filter(DT_* v, const IT_* idx, Index ue, cudaStream_t s = 0)
95 if(ue == Index(0)) return;
96 const unsigned bs = 256u;
97 cuda_unit_filter_zero<DT_, IT_><<<grid_for(ue, bs), bs, 0, s>>>(v, idx, ue);
101 template<typename DT_>
102 static void launch_comp_prod(DT_* v, const DT_* f, Index n, cudaStream_t s = 0)
104 if(n == Index(0)) return;
105 const unsigned bs = 256u;
106 cuda_comp_prod<DT_><<<grid_for(n, bs), bs, 0, s>>>(v, f, n);
110 // ---- resolved (device-pointer) views of a meta matrix ------------------------------------
112 template<typename DT_, typename IT_>
119 int block_height, block_width;
120 Index num_rows, num_cols, num_nnz;
121 int out_comp, in_comp;
124 /// resolve the cuda views of every non-empty block of a meta matrix; keeps the views alive
125 template<typename DT_, typename IT_, int NC_>
126 static std::vector<ResolvedBlock<DT_, IT_>> resolve_matrix(
127 const RichardsonHelper::MetaMatrix<DT_, IT_, NC_, NC_>& mat,
128 std::vector<Memory::TypedView<DT_>>& val_views,
129 std::vector<Memory::TypedView<IT_>>& idx_views)
131 std::vector<ResolvedBlock<DT_, IT_>> out;
132 for(int r = 0; r < NC_; ++r)
134 for(int c = 0; c < NC_; ++c)
136 const auto& b = mat.at(r, c);
139 val_views.emplace_back(b.val->view(Memory::Location::cuda, Memory::Access::read));
140 idx_views.emplace_back(b.row->view(Memory::Location::cuda, Memory::Access::read));
141 idx_views.emplace_back(b.col->view(Memory::Location::cuda, Memory::Access::read));
142 ResolvedBlock<DT_, IT_> rb;
143 rb.val = val_views.back().get_r();
144 rb.row = idx_views[idx_views.size() - 2u].get_r();
145 rb.col = idx_views[idx_views.size() - 1u].get_r();
146 rb.workspace = b.workspace;
147 rb.block_height = b.block_height;
148 rb.block_width = b.block_width;
149 rb.num_rows = b.num_rows;
150 rb.num_cols = b.num_cols;
151 rb.num_nnz = b.num_nnz;
161 * \brief Meta SpMV accumulate: out += alpha * Mat * in.
163 * \c out must be pre-initialized (to the rhs for a defect, or to zero for a preconditioner
164 * apply); every live block accumulates in place via exec_cuda_impl with y == r. This is the sole
165 * "how the SpMV runs" seam — a future fused meta-kernel replaces this body only.
167 template<typename DT_, typename IT_>
168 static void spmv_accumulate(DT_* const* out_ptr, const DT_* const* in_ptr,
169 const std::vector<ResolvedBlock<DT_, IT_>>& blocks, DT_ alpha)
171 for(const auto& b : blocks)
173 DT_* r = out_ptr[b.out_comp];
174 const DT_* x = in_ptr[b.in_comp];
175 // r = y + alpha * A * x with y == r => r += alpha * A * x (native (bh x bw) BCSR SpMV),
176 // using the block's persistent cuSPARSE workspace (required by the BSR SpMV path on CUDA >= 13)
177 LAFEM::Arch::MatVecMultBCSRDense::exec_cuda_impl<DT_, IT_>(
178 b.workspace, r, alpha, x, /*y*/ r, b.val, b.col, b.row,
179 b.num_rows, b.num_cols, b.num_nnz, b.block_height, b.block_width, false);
182 } // namespace Intern
184 // ---- single-rank (no synchronization) driver ----------------------------------------------
186 template<typename DT_, typename IT_, int NC_>
187 FEAT::Solver::Status cuda_apply_amavanka_richardson_seq(
188 const RichardsonHelper::RichardsonApplyInfo<DT_, IT_, NC_>& info,
189 RichardsonHelper::RichardsonStatus<DT_>& status)
191 using namespace Intern;
193 // resolve the persistent component vectors once (pointers are stable across iterations)
194 std::vector<Memory::TypedView<DT_>> keep; // keeps all vector views alive
195 keep.reserve(std::size_t(NC_) * 4u);
196 std::array<DT_*, NC_> sol{}, def{}, cor{};
197 std::array<const DT_*, NC_> rhs{};
198 std::array<Index, NC_> rawlen{};
199 for(int c = 0; c < NC_; ++c)
201 rawlen[c] = info.components[c].size_raw();
202 keep.emplace_back(info.vec_sol[c]->view(Memory::Location::cuda, Memory::Access::read_write));
203 sol[c] = keep.back().get_w();
204 keep.emplace_back(info.vec_def[c]->view(Memory::Location::cuda, Memory::Access::read_write));
205 def[c] = keep.back().get_w();
206 keep.emplace_back(info.vec_cor[c]->view(Memory::Location::cuda, Memory::Access::read_write));
207 cor[c] = keep.back().get_w();
208 keep.emplace_back(info.vec_rhs[c]->view(Memory::Location::cuda, Memory::Access::read));
209 rhs[c] = keep.back().get_r();
212 // resolve the unit-filter index arrays
213 std::vector<Memory::TypedView<IT_>> filter_views;
214 filter_views.reserve(NC_);
215 std::array<const IT_*, NC_> filt_idx{};
216 std::array<Index, NC_> filt_ue{};
217 for(int c = 0; c < NC_; ++c)
219 filt_ue[c] = info.def_filters[c].used_elements;
220 if(filt_ue[c] > Index(0) && info.def_filters[c].ind != nullptr)
222 filter_views.emplace_back(info.def_filters[c].ind->view(Memory::Location::cuda, Memory::Access::read));
223 filt_idx[c] = filter_views.back().get_r();
227 // resolve the matrix blocks once
228 std::vector<Memory::TypedView<DT_>> sys_val, van_val;
229 std::vector<Memory::TypedView<IT_>> sys_idx, van_idx;
230 const auto sys_blocks = resolve_matrix<DT_, IT_, NC_>(info.mat_sys, sys_val, sys_idx);
231 const auto van_blocks = resolve_matrix<DT_, IT_, NC_>(info.mat_vanka, van_val, van_idx);
233 const Index steps = Math::max(info.max_iter, Index(1));
234 for(Index step = 0; step < steps; ++step)
236 // d = rhs - A*u : start from d = rhs, then accumulate -A*u in place
237 for(int c = 0; c < NC_; ++c)
238 cudaCheck(cudaMemcpyAsync(def[c], rhs[c], rawlen[c] * sizeof(DT_), cudaMemcpyDeviceToDevice), "def<-rhs");
239 spmv_accumulate<DT_, IT_>(def.data(), sol.data(), sys_blocks, -DT_(1));
240 for(int c = 0; c < NC_; ++c)
241 launch_filter<DT_, IT_>(def[c], filt_idx[c], filt_ue[c]);
243 // cor = V*d : start from cor = 0, then accumulate +V*d in place
244 for(int c = 0; c < NC_; ++c)
245 cudaCheck(cudaMemsetAsync(cor[c], 0, rawlen[c] * sizeof(DT_)), "cor<-0");
246 spmv_accumulate<DT_, IT_>(cor.data(), def.data(), van_blocks, DT_(1));
247 for(int c = 0; c < NC_; ++c)
248 launch_filter<DT_, IT_>(cor[c], filt_idx[c], filt_ue[c]);
251 for(int c = 0; c < NC_; ++c)
252 launch_axpy<DT_>(sol[c], info.omega, cor[c], rawlen[c]);
254 cudaCheck(cudaDeviceSynchronize(), "richardson seq sync");
256 status.num_iter = steps;
257 status.def_norm = DT_(0);
258 status.def_init = DT_(0);
259 return FEAT::Solver::Status::success;
262 // ---- distributed driver: per-component hand-rolled sync_0 / sync_1 -------------------------
266 /// per-component communication buffers for one gate
267 template<typename DT_>
270 std::vector<DT_*> dev; // one device buffer per neighbor
271 std::vector<DT_*> host_send; // pinned host send buffer per neighbor
272 std::vector<DT_*> host_recv; // pinned host recv buffer per neighbor
275 template<typename DT_, typename IT_>
276 static CommBuffers<DT_> setup_buffers(const RichardsonHelper::GateWrapper<DT_, IT_>& g, int bs)
279 const std::size_t n = g.ranks.size();
280 b.dev.resize(n, nullptr);
281 b.host_send.resize(n, nullptr);
282 b.host_recv.resize(n, nullptr);
283 for(std::size_t k = 0; k < n; ++k)
285 if(g.mirror_size[k] == Index(0)) // neighbor with no shared DOFs for this component (e.g. discontinuous pressure)
287 const std::size_t bytes = g.mirror_size[k] * Index(bs) * sizeof(DT_);
288 cudaCheck(cudaMalloc(&b.dev[k], bytes), "cudaMalloc");
289 cudaCheck(cudaMallocHost(&b.host_send[k], bytes), "cudaMallocHost");
290 cudaCheck(cudaMallocHost(&b.host_recv[k], bytes), "cudaMallocHost");
295 template<typename DT_>
296 static void free_buffers(CommBuffers<DT_>& b)
298 for(auto* p : b.dev) if(p) cudaFree(p);
299 for(auto* p : b.host_send) if(p) cudaFreeHost(p);
300 for(auto* p : b.host_recv) if(p) cudaFreeHost(p);
301 b.dev.clear(); b.host_send.clear(); b.host_recv.clear();
304 /// additive type-0 synchronization of one component vector \p v over its gate
305 template<typename DT_, typename IT_>
306 static void sync_0_component(DT_* v, int bs, const RichardsonHelper::GateWrapper<DT_, IT_>& g,
307 CommBuffers<DT_>& buf, const std::vector<const IT_*>& mirror_ptr)
309 const std::size_t n = g.ranks.size();
312 Dist::Comm& comm = *g.comm;
313 const unsigned block = 128u;
315 // gather local shared values into the send buffers and copy to host
316 for(std::size_t k = 0; k < n; ++k)
318 const Index nodes = g.mirror_size[k];
319 if(nodes == Index(0)) // no shared DOFs with this neighbor for this component
321 const Index total = nodes * Index(bs);
322 cuda_gather<DT_, IT_><<<grid_for(total, block), block>>>(buf.dev[k], mirror_ptr[k], nodes, v, bs);
324 cudaCheck(cudaMemcpyAsync(buf.host_send[k], buf.dev[k], total * sizeof(DT_), cudaMemcpyDeviceToHost), "gather D2H");
326 cudaCheck(cudaDeviceSynchronize(), "sync_0 gather");
328 // exchange (only neighbors that actually share DOFs for this component); req_k maps a request
329 // slot back to its neighbor index for the wait_any-driven scatter below
330 Dist::RequestVector recv_reqs, send_reqs;
331 std::vector<std::size_t> req_k;
332 recv_reqs.reserve(n); send_reqs.reserve(n); req_k.reserve(n);
333 for(std::size_t k = 0; k < n; ++k)
335 if(g.mirror_size[k] == Index(0))
337 recv_reqs.push_back(comm.irecv(buf.host_recv[k], g.mirror_size[k] * Index(bs), g.ranks[k]));
340 for(std::size_t k = 0; k < n; ++k)
342 if(g.mirror_size[k] == Index(0))
344 send_reqs.push_back(comm.isend(buf.host_send[k], g.mirror_size[k] * Index(bs), g.ranks[k]));
347 // scatter-add received neighbor contributions back
348 for(std::size_t ridx = 0; recv_reqs.wait_any(ridx); )
350 const std::size_t k = req_k[ridx];
351 const Index nodes = g.mirror_size[k];
352 const Index total = nodes * Index(bs);
353 cudaCheck(cudaMemcpyAsync(buf.dev[k], buf.host_recv[k], total * sizeof(DT_), cudaMemcpyHostToDevice), "recv H2D");
354 cudaCheck(cudaDeviceSynchronize(), "recv H2D sync");
355 cuda_scatter_add<DT_, IT_><<<grid_for(total, block), block>>>(v, buf.dev[k], mirror_ptr[k], nodes, bs);
358 cudaCheck(cudaDeviceSynchronize(), "sync_0 scatter");
359 send_reqs.wait_all();
361 } // namespace Intern
363 template<typename DT_, typename IT_, int NC_>
364 FEAT::Solver::Status cuda_apply_amavanka_richardson_parallel(
365 const RichardsonHelper::RichardsonApplyInfo<DT_, IT_, NC_>& info,
366 RichardsonHelper::RichardsonStatus<DT_>& status)
368 using namespace Intern;
370 // resolve component vectors + rawlen + block sizes
371 std::vector<Memory::TypedView<DT_>> keep;
372 keep.reserve(std::size_t(NC_) * 5u);
373 std::array<DT_*, NC_> sol{}, def{}, cor{};
374 std::array<const DT_*, NC_> rhs{};
375 std::array<const DT_*, NC_> freqs{};
376 std::array<Index, NC_> rawlen{};
377 std::array<int, NC_> bsz{};
378 for(int c = 0; c < NC_; ++c)
380 bsz[c] = info.components[c].block_size;
381 rawlen[c] = info.components[c].size_raw();
382 keep.emplace_back(info.vec_sol[c]->view(Memory::Location::cuda, Memory::Access::read_write));
383 sol[c] = keep.back().get_w();
384 keep.emplace_back(info.vec_def[c]->view(Memory::Location::cuda, Memory::Access::read_write));
385 def[c] = keep.back().get_w();
386 keep.emplace_back(info.vec_cor[c]->view(Memory::Location::cuda, Memory::Access::read_write));
387 cor[c] = keep.back().get_w();
388 keep.emplace_back(info.vec_rhs[c]->view(Memory::Location::cuda, Memory::Access::read));
389 rhs[c] = keep.back().get_r();
390 if(!info.gates[c].empty() && info.gates[c].freqs != nullptr)
392 keep.emplace_back(info.gates[c].freqs->view(Memory::Location::cuda, Memory::Access::read));
393 freqs[c] = keep.back().get_r();
397 // resolve unit filters
398 std::vector<Memory::TypedView<IT_>> filter_views;
399 std::array<const IT_*, NC_> filt_idx{};
400 std::array<Index, NC_> filt_ue{};
401 for(int c = 0; c < NC_; ++c)
403 filt_ue[c] = info.def_filters[c].used_elements;
404 if(filt_ue[c] > Index(0) && info.def_filters[c].ind != nullptr)
406 filter_views.emplace_back(info.def_filters[c].ind->view(Memory::Location::cuda, Memory::Access::read));
407 filt_idx[c] = filter_views.back().get_r();
411 // resolve matrix blocks
412 std::vector<Memory::TypedView<DT_>> sys_val, van_val;
413 std::vector<Memory::TypedView<IT_>> sys_idx, van_idx;
414 const auto sys_blocks = resolve_matrix<DT_, IT_, NC_>(info.mat_sys, sys_val, sys_idx);
415 const auto van_blocks = resolve_matrix<DT_, IT_, NC_>(info.mat_vanka, van_val, van_idx);
417 // resolve mirror index arrays + set up per-component comm buffers (once)
418 std::vector<Memory::TypedView<IT_>> mirror_views;
419 std::array<std::vector<const IT_*>, NC_> mirror_ptr;
420 std::array<CommBuffers<DT_>, NC_> buffers;
421 for(int c = 0; c < NC_; ++c)
423 const auto& g = info.gates[c];
424 for(std::size_t k = 0; k < g.ranks.size(); ++k)
426 // a hollow mirror (no shared DOFs for this component, e.g. discontinuous pressure) has a
427 // null index arbiter — keep the slot aligned with ranks but do not resolve/use it
428 if(g.mirror_size[k] > Index(0) && g.mirror_idx[k] != nullptr)
430 mirror_views.emplace_back(g.mirror_idx[k]->view(Memory::Location::cuda, Memory::Access::read));
431 mirror_ptr[c].push_back(mirror_views.back().get_r());
434 mirror_ptr[c].push_back(nullptr);
437 buffers[c] = setup_buffers<DT_, IT_>(g, bsz[c]);
440 const Index steps = Math::max(info.max_iter, Index(1));
441 for(Index step = 0; step < steps; ++step)
443 // d = rhs - A*u (local), then sync_0 the additive (type-0) result, then filter.
444 // Note: the defect is reconciled with sync_0 (no frequency weighting); frequency scaling
445 // (from_1_to_0) belongs only to the correction's sync_1 below.
446 for(int c = 0; c < NC_; ++c)
447 cudaCheck(cudaMemcpyAsync(def[c], rhs[c], rawlen[c] * sizeof(DT_), cudaMemcpyDeviceToDevice), "def<-rhs");
448 for(int c = 0; c < NC_; ++c)
450 if(!info.gates[c].empty())
452 launch_comp_prod<DT_>(def[c], freqs[c], rawlen[c]); // from_1_to_0
455 spmv_accumulate<DT_, IT_>(def.data(), sol.data(), sys_blocks, -DT_(1));
456 cudaCheck(cudaDeviceSynchronize(), "sys spmv");
457 for(int c = 0; c < NC_; ++c)
458 sync_0_component<DT_, IT_>(def[c], bsz[c], info.gates[c], buffers[c], mirror_ptr[c]);
459 for(int c = 0; c < NC_; ++c)
460 launch_filter<DT_, IT_>(def[c], filt_idx[c], filt_ue[c]);
462 // cor = V*d (local), then sync_1 (freq scale + sync_0), then filter
463 for(int c = 0; c < NC_; ++c)
464 cudaCheck(cudaMemsetAsync(cor[c], 0, rawlen[c] * sizeof(DT_)), "cor<-0");
465 spmv_accumulate<DT_, IT_>(cor.data(), def.data(), van_blocks, DT_(1));
466 cudaCheck(cudaDeviceSynchronize(), "vanka spmv");
467 for(int c = 0; c < NC_; ++c)
469 if(!info.gates[c].empty())
471 launch_comp_prod<DT_>(cor[c], freqs[c], rawlen[c]); // from_1_to_0
472 sync_0_component<DT_, IT_>(cor[c], bsz[c], info.gates[c], buffers[c], mirror_ptr[c]);
475 for(int c = 0; c < NC_; ++c)
476 launch_filter<DT_, IT_>(cor[c], filt_idx[c], filt_ue[c]);
479 for(int c = 0; c < NC_; ++c)
480 launch_axpy<DT_>(sol[c], info.omega, cor[c], rawlen[c]);
482 cudaCheck(cudaDeviceSynchronize(), "richardson parallel sync");
484 for(int c = 0; c < NC_; ++c)
485 free_buffers<DT_>(buffers[c]);
487 status.num_iter = steps;
488 status.def_norm = DT_(0);
489 status.def_init = DT_(0);
490 return FEAT::Solver::Status::success;
493 // ---- explicit instantiations (saddle-point => NC_ == 2) -----------------------------------
495 template FEAT::Solver::Status cuda_apply_amavanka_richardson_seq<double, std::uint32_t, 2>(
496 const RichardsonHelper::RichardsonApplyInfo<double, std::uint32_t, 2>&, RichardsonHelper::RichardsonStatus<double>&);
497 template FEAT::Solver::Status cuda_apply_amavanka_richardson_seq<double, std::uint64_t, 2>(
498 const RichardsonHelper::RichardsonApplyInfo<double, std::uint64_t, 2>&, RichardsonHelper::RichardsonStatus<double>&);
499 template FEAT::Solver::Status cuda_apply_amavanka_richardson_seq<float, std::uint32_t, 2>(
500 const RichardsonHelper::RichardsonApplyInfo<float, std::uint32_t, 2>&, RichardsonHelper::RichardsonStatus<float>&);
501 template FEAT::Solver::Status cuda_apply_amavanka_richardson_seq<float, std::uint64_t, 2>(
502 const RichardsonHelper::RichardsonApplyInfo<float, std::uint64_t, 2>&, RichardsonHelper::RichardsonStatus<float>&);
504 template FEAT::Solver::Status cuda_apply_amavanka_richardson_parallel<double, std::uint32_t, 2>(
505 const RichardsonHelper::RichardsonApplyInfo<double, std::uint32_t, 2>&, RichardsonHelper::RichardsonStatus<double>&);
506 template FEAT::Solver::Status cuda_apply_amavanka_richardson_parallel<double, std::uint64_t, 2>(
507 const RichardsonHelper::RichardsonApplyInfo<double, std::uint64_t, 2>&, RichardsonHelper::RichardsonStatus<double>&);
508 template FEAT::Solver::Status cuda_apply_amavanka_richardson_parallel<float, std::uint32_t, 2>(
509 const RichardsonHelper::RichardsonApplyInfo<float, std::uint32_t, 2>&, RichardsonHelper::RichardsonStatus<float>&);
510 template FEAT::Solver::Status cuda_apply_amavanka_richardson_parallel<float, std::uint64_t, 2>(
511 const RichardsonHelper::RichardsonApplyInfo<float, std::uint64_t, 2>&, RichardsonHelper::RichardsonStatus<float>&);
512} // namespace FEAT::Solver::VankaRichardson