NeoN
A framework for CFD software
Loading...
Searching...
No Matches
ginkgo.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2024 - 2026 NeoN authors
2//
3// SPDX-License-Identifier: MIT
4
5#pragma once
6
7#if NF_WITH_GINKGO
8
9#include <chrono>
10#include <optional>
11#include <string>
12
13#include <ginkgo/ginkgo.hpp>
14#include <ginkgo/extensions/kokkos.hpp>
15#include <ginkgo/extensions/config/json_config.hpp>
16
17#include "NeoN/fields/field.hpp"
23#include "NeoN/linearAlgebra/ginkgo/mergedPgm.hpp" // MergedPgm mergeLevels-style coarsening
24
25
26namespace NeoN::la::ginkgo
27{
28
29std::shared_ptr<gko::Executor> getGkoExecutor(Executor exec);
30
31gko::config::pnode parse(const Dictionary& dict);
32
34template<typename NeoNMatrixType>
35std::shared_ptr<const gko::LinOp> createGkoMtx(const NeoNMatrixType& mtx);
36
37#ifdef NF_WITH_MPI_SUPPORT
39
40template<typename IndexType>
41std::shared_ptr<const gko::LinOp> createGkoMtxDist(
42 std::shared_ptr<const gko::Executor> exec,
43 const gko::experimental::mpi::communicator& comm,
44 const CSRMatrix<scalar, IndexType>& mtx,
45 const COOMatrix<scalar, IndexType>& bmtx,
46 const CommunicationPattern& commPattern,
47 std::shared_ptr<gko::experimental::distributed::index_map<label, gko::int64>>& imapCache,
48 std::shared_ptr<gko::matrix::Coo<scalar, IndexType>>& nonLocalMtxCache,
49 std::shared_ptr<const gko::LinOp>& distMtxCache,
50 const scalar*& localValPtrCache
51);
52#endif // NF_WITH_MPI_SUPPORT
53
54template<typename T>
55gko::array<T> gkoArrayView(std::shared_ptr<const gko::Executor> exec, std::span<T> values)
56{
57 return gko::make_array_view(exec, values.size(), values.data());
58}
59
61template<typename T>
62std::shared_ptr<gko::matrix::Dense<scalar>>
63gkoVecView(std::shared_ptr<const gko::Executor> exec, T* ptr, localIdx s)
64{
65 constexpr sizeType cols = std::is_same_v<T, Vec3> ? 3 : 1;
66 auto size = static_cast<sizeType>(s);
67 return gko::share(gko::matrix::Dense<scalar>::create(
68 exec,
69 gko::dim<2> {size, cols},
70 gkoArrayView<scalar>(exec, std::span<scalar> {reinterpret_cast<scalar*>(ptr), cols * size}),
71 cols
72 ));
73}
74
76template<typename T>
77std::shared_ptr<const gko::matrix::Dense<scalar>>
78gkoVecView(std::shared_ptr<const gko::Executor> exec, const T* ptr, localIdx s)
79{
80 constexpr sizeType cols = std::is_same_v<T, Vec3> ? 3 : 1;
81 auto size = static_cast<sizeType>(s);
82 return gko::share(gko::matrix::Dense<scalar>::create_const(
83 exec,
84 gko::dim<2> {size, cols},
85 gko::array<scalar>::const_view(exec, cols * size, reinterpret_cast<const scalar*>(ptr)),
86 cols
87 ));
88}
89
91template<typename InType>
92scalar retrieve(const InType& in)
93{
94 using vec = gko::matrix::Dense<scalar>;
95 auto host = vec::create(in->get_executor()->get_master(), gko::dim<2> {1});
96 host->copy_from(in);
97 return host->at(0);
98}
99
105struct L1ResidualControl
106{
107 scalar tolerance;
108 scalar relTol;
109 gko::size_type maxIter;
110 gko::size_type minIter;
111 localIdx checkFrequency;
113};
114
121struct L1ResidualResult
122{
123 gko::size_type numIter = 0;
124 scalar initResNorm = 0.0;
125 scalar finalResNorm = 0.0;
126 scalar normFactor = 0.0;
127 bool fired = false;
128 // Per-column scaled residuals; populated only for multi-RHS (Vec3) solves (size == ncols).
129 std::vector<scalar> perColInitNorms;
130 std::vector<scalar> perColFinalNorms;
131};
132
138inline constexpr const char* l1CriterionKey = "neon::l1ScaledResidual";
139
147std::shared_ptr<gko::stop::CriterionFactory> makeL1CriterionFactory(
148 std::shared_ptr<const gko::Executor> exec,
149 const L1ResidualControl& control,
150 L1ResidualResult* report
151);
152
159scalar scaledL1Residual(
160 const gko::LinOp* mtx, const gko::LinOp* b, const gko::LinOp* x, scalar normFactor
161);
162
169L1ResidualResult solveWithL1Stop(
170 std::shared_ptr<const gko::Executor> exec,
171 std::shared_ptr<const gko::LinOp> mtx,
172 std::shared_ptr<const gko::matrix::Dense<scalar>> b,
173 std::shared_ptr<gko::matrix::Dense<scalar>> x,
174 gko::LinOp* solver,
175 const L1ResidualControl& control
176);
177
178#ifdef NF_WITH_MPI_SUPPORT
185L1ResidualResult solveWithL1StopDist(
186 std::shared_ptr<const gko::Executor> exec,
187 std::shared_ptr<const gko::LinOp> mtx,
188 std::shared_ptr<const gko::experimental::distributed::Vector<scalar>> b,
189 std::shared_ptr<gko::experimental::distributed::Vector<scalar>> x,
190 gko::LinOp* solver,
191 const L1ResidualControl& control
192);
193#endif
194
200inline bool readFlag(const Dictionary& cfg, const std::string& key, bool fallback)
201{
202 if (!cfg.contains(key)) return fallback;
203 if (cfg.isType<bool>(key)) return cfg.get<bool>(key);
204 if (cfg.isType<int>(key)) return cfg.get<int>(key) != 0;
205 if (cfg.isType<std::string>(key))
206 {
207 const std::string v = cfg.get<std::string>(key);
208 return v == "true" || v == "yes" || v == "on" || v == "1";
209 }
210 return false;
211}
212
221inline std::optional<L1ResidualControl> readL1ResidualControl(const Dictionary& cfg)
222{
223 if (!readFlag(cfg, "l1ScaledResidual", false))
224 {
225 return std::nullopt;
226 }
227
228 L1ResidualControl control {0.0, 0.0, 1000, 0, 1};
229
230 // criteria entries may be stored as int, label or scalar depending on source
231 auto readScalar = [](const Dictionary& d, const std::string& key, scalar fallback)
232 {
233 if (!d.contains(key)) return fallback;
234 if (d.isType<int>(key)) return scalar(d.get<int>(key));
235 if (d.isType<label>(key)) return scalar(d.get<label>(key));
236 return d.get<scalar>(key);
237 };
238 auto readInt = [](const Dictionary& d, const std::string& key, localIdx fallback)
239 {
240 if (!d.contains(key)) return fallback;
241 if (d.isType<int>(key)) return localIdx(d.get<int>(key));
242 if (d.isType<scalar>(key)) return localIdx(d.get<scalar>(key));
243 return d.get<localIdx>(key);
244 };
245
246 // OpenFOAM-style top-level keys (the configFile solver path keeps them: there is no
247 // mapped "criteria" subdict there). Read first so they seed the control...
248 control.tolerance = readScalar(cfg, "tolerance", control.tolerance);
249 control.relTol = readScalar(cfg, "relTol", control.relTol);
250 control.maxIter = readInt(cfg, "maxIter", control.maxIter);
251
252 // ...then let a mapped "criteria" subdict (Ginkgo-style keys) override when present,
253 // preserving the existing behaviour for fvSolution-mapped solvers.
254 if (cfg.contains("criteria"))
255 {
256 const Dictionary& criteria = cfg.subDict("criteria");
257 control.tolerance = readScalar(criteria, "absolute_residual_norm", control.tolerance);
258 control.relTol = readScalar(criteria, "initial_residual_norm", control.relTol);
259 control.maxIter = readInt(criteria, "iteration", control.maxIter);
260 }
261 control.minIter = readInt(cfg, "minIter", control.minIter);
262 control.checkFrequency = readInt(cfg, "checkFrequency", control.checkFrequency);
263
264 return control;
265}
266
271inline bool pnodeReferencesString(const gko::config::pnode& node, const std::string& name)
272{
273 using tag = gko::config::pnode::tag_t;
274 switch (node.get_tag())
275 {
276 case tag::string:
277 return node.get_string() == name;
278 case tag::array:
279 for (const auto& e : node.get_array())
280 if (pnodeReferencesString(e, name)) return true;
281 return false;
282 case tag::map:
283 for (const auto& kv : node.get_map())
284 if (pnodeReferencesString(kv.second, name)) return true;
285 return false;
286 default:
287 return false;
288 }
289}
290
291class GinkgoSolver : public SolverFactory::template Register<GinkgoSolver>
292{
293
294 using Base = SolverFactory::template Register<GinkgoSolver>;
295
296public:
297
298 GinkgoSolver(Executor exec, const Dictionary& solverConfig)
299 : Base(exec), gkoExec_(getGkoExecutor(exec)), coupled_(solverConfig.get("coupled", false)),
300 reuseSetup_(readFlag(solverConfig, "reuseSetup", true)),
301 l1Control_(readL1ResidualControl(solverConfig)), config_(parse(solverConfig))
302 {
303 // Register NeoN's L1-scaled residual criterion in the Ginkgo config registry so a
304 // configFile can name it (l1CriterionKey) in its "criteria" array. Only needed when
305 // the L1 stop is requested (l1ScaledResidual); the factory carries the tolerances and
306 // a report sink. If the parsed config actually references it, the criterion lives
307 // INSIDE the built solver (l1InConfig_) and reports via l1Report_; otherwise the
308 // existing post-hoc attach in solve() handles the flag-only case unchanged.
309 gko::config::registry reg(mergedPgmConfigMap<scalar>());
310 if (l1Control_)
311 {
312 l1CritFactory_ = makeL1CriterionFactory(gkoExec_, *l1Control_, &l1Report_);
313 reg.emplace(std::string(l1CriterionKey), l1CritFactory_);
314 l1InConfig_ = pnodeReferencesString(config_, l1CriterionKey);
315 }
316
317 // Register NeoN's MergedPgm coarseners (mergeLevels-style: merge k Pgm steps into one level
318 // via index-composed prolongations). A configFile's `mg_level` can then name them, e.g.
319 // "mg_level": ["neon::pgmMerge2"]. Named-registry pattern, same as the L1 criterion above.
320 // For other parameters (e.g. scale_correction) a config names the type itself, e.g.
321 // {"type": "neon::MergedPgm", "merge_levels": 2, "scale_correction": true}, which the
322 // registry's mergedPgmConfigMap parses.
323 // pgmMerge1 = merge_levels 1 = plain Pgm (single coarsening step), but via the SAME
324 // MergedPgm code path as 2/3 -- so the reuse (generate_reuse) and distributed branches
325 // behave identically across the merge-levels sweep, unlike swapping in native gko
326 // multigrid::Pgm.
327 reg.emplace("neon::pgmMerge1", makeMergedPgmFactory<scalar>(gkoExec_, 1));
328 reg.emplace("neon::pgmMerge2", makeMergedPgmFactory<scalar>(gkoExec_, 2));
329 reg.emplace("neon::pgmMerge3", makeMergedPgmFactory<scalar>(gkoExec_, 3));
330 reg.emplace("neon::pgmMerge4", makeMergedPgmFactory<scalar>(gkoExec_, 4));
331
332 // With reuseSetup, a preconditioner given as a config map is parsed as a factory of its
333 // own and generated through generate_reuse() in generateSolver(), since the Krylov solvers
334 // do not forward reuse to their preconditioner. Its type descriptor is the one the solver
335 // would pass to it, unless the config sets a value_type, which is then left to Ginkgo.
336 const auto td = gko::config::make_type_descriptor<scalar>();
337 auto gkoSolverConfig = config_;
338 const auto& precondConfig = config_.get("preconditioner");
339 if (reuseSetup_ && precondConfig.get_tag() == gko::config::pnode::tag_t::map
340 && !config_.get("value_type"))
341 {
342 precondFactory_ = gko::config::parse(precondConfig, reg, td).on(gkoExec_);
343 auto map = config_.get_map();
344 map.erase("preconditioner");
345 gkoSolverConfig = gko::config::pnode(map);
346 }
347 factory_ = gko::config::parse(gkoSolverConfig, reg, td).on(gkoExec_);
348 }
349
350 static std::string name() { return "Ginkgo"; }
351
352 static std::string doc() { return "TBD"; }
353
354 static std::string schema() { return "none"; }
355
356 virtual SolverStats solve(
357 const LinearSystem<scalar, scalar, CSRMatrix<scalar, localIdx>>& sys, Vector<scalar>& x
358 ) const final;
359
360 virtual SolverStats solve(
361 const LinearSystem<Vec3, Vec3, CSRMatrix<Vec3, localIdx>>& sys, Vector<Vec3>& x
362 ) const final;
363
364 virtual SolverStats solve(
365 const LinearSystem<scalar, Vec3, CSRMatrix<scalar, localIdx>, COOMatrix<scalar, localIdx>>&
366 sys,
367 Vector<Vec3>& x
368 ) const final;
369
370#ifdef NF_WITH_MPI_SUPPORT
371 virtual SolverStats solveDist(
372 const LinearSystem<scalar, scalar, CSRMatrix<scalar, localIdx>>& sys, Vector<scalar>& x
373 ) const final;
374
375 virtual SolverStats solveDist(
376 const LinearSystem<Vec3, Vec3, CSRMatrix<Vec3, localIdx>>& sys, Vector<Vec3>& x
377 ) const final;
378
379 virtual SolverStats solveDist(
380 const LinearSystem<scalar, Vec3, CSRMatrix<scalar, localIdx>, COOMatrix<scalar, localIdx>>&
381 sys,
382 Vector<Vec3>& x
383 ) const final;
384#endif
385
386 // TODO why use a smart pointer here?
387 virtual std::unique_ptr<SolverFactory> clone() const final
388 {
389 NF_ERROR_EXIT("Not implemented");
390 return {};
391 }
392
393private:
394
403 std::unique_ptr<gko::LinOp> generateSolver(std::shared_ptr<const gko::LinOp> mtx) const;
404
405 std::shared_ptr<const gko::Executor> gkoExec_;
406 bool coupled_;
407 // Reuse the preconditioner/multigrid setup across solves (dictionary key reuseSetup).
408 bool reuseSetup_;
409 std::optional<L1ResidualControl> l1Control_;
410 gko::config::pnode config_;
411 std::shared_ptr<const gko::LinOpFactory> factory_;
412 // Preconditioner factory split off the config for reuse (null without reuseSetup or when the
413 // config has no preconditioner map); generateSolver() attaches what it generates.
414 std::shared_ptr<const gko::LinOpFactory> precondFactory_;
415 // Reuse data of precondFactory_, or of factory_ without one; null until the first solve.
416 mutable std::unique_ptr<gko::LinOpFactory::ReuseData> reuseData_;
417 // L1-scaled residual criterion registered into the config registry (l1Control_ set).
418 std::shared_ptr<gko::stop::CriterionFactory> l1CritFactory_;
419 // True when config_ names the L1 criterion, so it is built into factory_'s solver and
420 // reports through l1Report_ (the in-config path); false keeps the post-hoc attach.
421 bool l1InConfig_ = false;
422 // Report sink the in-config criterion writes its scaled L1 residual / iters into.
423 mutable L1ResidualResult l1Report_;
424
425 /* @brief Replace the solve's unscaled norms with the in-config L1 criterion's scaled ones,
426 * if that criterion ran during the solve. @p mtx, @p b and @p x (the solution after the
427 * solve) refresh the final residual when the report is stale.
428 */
429 SolverStatsEntry withL1Report(
430 SolverStatsEntry entry, const gko::LinOp* mtx, const gko::LinOp* b, const gko::LinOp* x
431 ) const;
432#ifdef NF_WITH_MPI_SUPPORT
433 // Both caches are null until the first solve; after that topology is fixed.
434 mutable std::shared_ptr<gko::experimental::distributed::index_map<label, gko::int64>>
435 cachedImap_;
436 mutable std::shared_ptr<gko::matrix::Coo<scalar, localIdx>> cachedNonLocalMtx_;
437 // Distributed-matrix wrapper and the local value buffer it views. While the buffer is unchanged
438 // (NeoN re-assembles in place), createGkoMtxDist returns the wrapper instead of rebuilding it,
439 // which would redo Ginkgo's Csr load-balancing analysis and the row-gatherer setup every solve.
440 mutable std::shared_ptr<const gko::LinOp> cachedDistMtx_;
441 mutable const scalar* cachedLocalValPtr_ = nullptr;
442#endif
443};
444
445
446}
447
448#endif
#define NF_ERROR_EXIT(message)
Macro for printing an error message and aborting the program.
Definition error.hpp:90
std::optional< la::SolverStats > solve(Expression< typename VectorType::ElementType, IndexType > &exp, VectorType &solution, scalar t, scalar dt, const Dictionary &fvSchemes, const Dictionary &fvSolution, std::vector< const PostAssemblyBase< typename VectorType::ElementType, IndexType > * > p={})
Definition solver.hpp:98
void map(ContType< ValueType > &cont, const Inner inner, std::pair< localIdx, localIdx > range={0, 0})
Map a field using a specific executor.
float scalar
Definition scalar.hpp:17
std::size_t sizeType
Definition label.hpp:56
const std::string & name(const NeoN::Document &doc)
Retrieves the name of a Document.
int32_t localIdx
Definition label.hpp:50