MueLu Version of the Day
Loading...
Searching...
No Matches
MueLu_InverseApproximationFactory_def.hpp
Go to the documentation of this file.
1// @HEADER
2// *****************************************************************************
3// MueLu: A package for multigrid based preconditioning
4//
5// Copyright 2012 NTESS and the MueLu contributors.
6// SPDX-License-Identifier: BSD-3-Clause
7// *****************************************************************************
8// @HEADER
9
10#ifndef MUELU_INVERSEAPPROXIMATIONFACTORY_DEF_HPP_
11#define MUELU_INVERSEAPPROXIMATIONFACTORY_DEF_HPP_
12
13#include <Xpetra_BlockedCrsMatrix.hpp>
14#include <Xpetra_CrsGraph.hpp>
15#include <Xpetra_CrsMatrixWrap.hpp>
16#include <Xpetra_CrsMatrix.hpp>
17#include <Xpetra_VectorFactory.hpp>
18#include <Xpetra_MatrixFactory.hpp>
19#include <Xpetra_Matrix.hpp>
20
21#include "Kokkos_Sort.hpp"
22#include "KokkosBlas1_set.hpp"
23#include "KokkosBatched_QR_Decl.hpp"
24#include "KokkosBatched_ApplyQ_Decl.hpp"
25#include "KokkosBatched_Trsv_Decl.hpp"
26#include "KokkosBatched_Util.hpp"
27#include <KokkosKernels_SimpleUtils.hpp>
28
29#include "MueLu_Level.hpp"
30#include "MueLu_Monitor.hpp"
31#include "MueLu_Utilities.hpp"
33
34#if KOKKOSKERNELS_VERSION < 50200
35#include "Teuchos_SerialDenseVector.hpp"
36#include "Teuchos_SerialDenseMatrix.hpp"
37#include "Teuchos_SerialQRDenseSolver.hpp"
38#endif
39
40namespace MueLu {
41
42template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
44 RCP<ParameterList> validParamList = rcp(new ParameterList());
45 using Magnitude = typename Teuchos::ScalarTraits<Scalar>::magnitudeType;
46
47 validParamList->set<RCP<const FactoryBase>>("A", NoFactory::getRCP(), "Matrix to build the approximate inverse on.\n");
48
49 validParamList->set<std::string>("inverse: approximation type", "diagonal", "Method used to approximate the inverse.");
50 validParamList->set<Magnitude>("inverse: drop tolerance", 0.0, "Values below this threshold are dropped from the matrix (or fixed if diagonal fixing is active).");
51 validParamList->set<bool>("inverse: fixing", false, "Keep diagonal and fix small entries with 1.0. Only used when sparse inverse method is either diagonal or lumping.");
52
53 return validParamList;
54}
55
56template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
60
61template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
63 FactoryMonitor m(*this, "Build", currentLevel);
64
65 using STS = Teuchos::ScalarTraits<SC>;
66 const SC one = STS::one();
67 using Magnitude = typename Teuchos::ScalarTraits<Scalar>::magnitudeType;
68
69 const ParameterList& pL = GetParameterList();
70 const bool fixing = pL.get<bool>("inverse: fixing");
71
72 // check which approximation type to use
73 const std::string method = pL.get<std::string>("inverse: approximation type");
74 TEUCHOS_TEST_FOR_EXCEPTION(method != "diagonal" && method != "lumping" && method != "sparseapproxinverse" && method != "factoredsparseapproxinverse", Exceptions::RuntimeError,
75 "MueLu::InverseApproximationFactory::Build: Approximation type can be 'diagonal' or 'lumping' or "
76 "'sparseapproxinverse' or 'factoredsparseapproxinverse'.");
77
78 RCP<Matrix> A = Get<RCP<Matrix>>(currentLevel, "A");
79 RCP<BlockedCrsMatrix> bA = Teuchos::rcp_dynamic_cast<BlockedCrsMatrix>(A);
80 const bool isBlocked = (bA == Teuchos::null ? false : true);
81
82 // if blocked operator is used, defaults to A(0,0)
83 if (isBlocked) A = bA->getMatrix(0, 0);
84
85 Magnitude tol = pL.get<Magnitude>("inverse: drop tolerance");
86 RCP<Matrix> Ainv = Teuchos::null;
87
88 if (method == "diagonal") {
89 const auto diag = VectorFactory::Build(A->getRangeMap(), true);
90 A->getLocalDiagCopy(*diag);
91 const RCP<const Vector> D = (!fixing ? Utilities::GetInverse(diag) : Utilities::GetInverse(diag, tol, one));
92 Ainv = MatrixFactory::Build(D);
93 } else if (method == "lumping") {
94 const auto diag = Utilities::GetLumpedMatrixDiagonal(*A);
95 const RCP<const Vector> D = (!fixing ? Utilities::GetInverse(diag) : Utilities::GetInverse(diag, tol, one));
96 Ainv = MatrixFactory::Build(D);
97#if KOKKOSKERNELS_VERSION >= 50200
98 } else if (method == "sparseapproxinverse") {
99#else
100 } else if ((method == "sparseapproxinverse") || (method == "factoredsparseapproxinverse")) {
101 if (method == "factoredsparseapproxinverse")
102 GetOStream(Warnings) << "Method \"factoredsparseapproxinverse\" requires KokkosKernels >= 5.2. Falling back to \"sparseapproxinverse\".";
103#endif
104 RCP<CrsGraph> sparsityPattern = Utilities::GetThresholdedGraph(A, tol, true);
105 if (IsPrint(Statistics1)) {
106 sparsityPattern->computeGlobalConstants();
107 GetOStream(Statistics1) << "NNZ Graph(A): " << A->getCrsGraph()->getGlobalNumEntries() << " , NNZ Tresholded Graph(A): " << sparsityPattern->getGlobalNumEntries() << std::endl;
108 }
109 RCP<Matrix> pAinv = GetSparseInverse(A, sparsityPattern);
110 if (tol != STS::magnitude(STS::zero()))
111 Ainv = Utilities::GetThresholdedMatrix(pAinv, tol, true);
112 else
113 Ainv = pAinv;
114 if (IsPrint(Statistics1)) {
115 rcp_const_cast<CrsGraph>(Ainv->getCrsGraph())->computeGlobalConstants();
116 GetOStream(Statistics1) << "NNZ Ainv: " << pAinv->getGlobalNumEntries() << ", NNZ Tresholded Ainv (parameter: " << tol << "): " << Ainv->getGlobalNumEntries() << std::endl;
117 }
118 }
119#if KOKKOSKERNELS_VERSION >= 50200
120 else if (method == "factoredsparseapproxinverse") {
121 RCP<CrsGraph> sparsityPattern = Utilities::GetThresholdedLowerTriangularGraph(A, tol, true);
122 if (IsPrint(Statistics1)) {
123 sparsityPattern->computeGlobalConstants();
124 GetOStream(Statistics1) << "NNZ Graph(A): " << A->getCrsGraph()->getGlobalNumEntries() << " , NNZ Tresholded Graph(triLower(A)): " << sparsityPattern->getGlobalNumEntries() << std::endl;
125 }
126 RCP<Matrix> pLinvFactor = GetFactoredSparseInverse(A, sparsityPattern);
127 RCP<Matrix> LinvFactor;
128 if (tol != STS::magnitude(STS::zero()))
129 LinvFactor = Utilities::GetThresholdedMatrix(pLinvFactor, tol, true);
130 else
131 LinvFactor = pLinvFactor;
132 // To create the inverse from the inverse factor, we need to multiply Linv' * LinvFactor. Of course, we could
133 // save a fair amount of storage by delaying this to when we actually need it as Linv' * LinvFactor has
134 // many more nonzeros than just Linv. One other thing, I'm explicitly using the Transpose computation as opposed to
135 // setting one of the booleans to true in the MatrixMatrix:Multiply. There are some comments about true/false combinations
136 // that don't work, so I decided not to push my luck here.
137
138 RCP<Matrix> LinvTrans = Utilities::Transpose(*LinvFactor, true);
139 Ainv = Xpetra::MatrixMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Multiply(*LinvTrans, false, *LinvFactor, false, GetOStream(Statistics2), true, true, std::string("Ainv"));
140
141 if (IsPrint(Statistics1)) {
142 rcp_const_cast<CrsGraph>(Ainv->getCrsGraph())->computeGlobalConstants();
143 GetOStream(Statistics1) << "NNZ Linv: " << LinvFactor->getGlobalNumEntries() << ", NNZ Tresholded Linv (parameter: " << tol << "): " << pLinvFactor->getGlobalNumEntries() << std::endl;
144 }
145 }
146#endif
147
148 GetOStream(Statistics1) << "Approximate inverse calculated by: " << method << "." << std::endl;
149 GetOStream(Statistics1) << "Ainv has " << Ainv->getGlobalNumRows() << "x" << Ainv->getGlobalNumCols() << " rows and columns." << std::endl;
150
151 Set(currentLevel, "Ainv", Ainv);
152}
153
154#if KOKKOSKERNELS_VERSION >= 50200
155
156template <class local_matrix_type>
157class LocalSPAIFunctor {
158 private:
159 using scalar_type = typename local_matrix_type::value_type;
160 using local_ordinal_type = typename local_matrix_type::ordinal_type;
161 using execution_space = typename local_matrix_type::execution_space;
162 using impl_scalar_type = typename KokkosKernels::ArithTraits<scalar_type>::val_type;
163 using impl_ATS = KokkosKernels::ArithTraits<impl_scalar_type>;
164
165 public:
166 using shared_matrix = Kokkos::View<impl_scalar_type**, typename execution_space::scratch_memory_space, Kokkos::MemoryUnmanaged>;
167 using shared_vector = Kokkos::View<impl_scalar_type*, typename execution_space::scratch_memory_space, Kokkos::MemoryUnmanaged>;
168 using shared_lo_vector = Kokkos::View<local_ordinal_type*, typename execution_space::scratch_memory_space, Kokkos::MemoryUnmanaged>;
169
170 private:
171 const local_matrix_type lclA;
172 local_matrix_type lclAinv;
173 const local_ordinal_type maxUniqueColEntries;
174 const int scratchLevel;
175
176 public:
177 LocalSPAIFunctor(const local_matrix_type& lclA_, local_matrix_type& lclAinv_, local_ordinal_type maxUniqueColEntries_, int scratchLevel_)
178 : lclA(lclA_)
179 , lclAinv(lclAinv_)
180 , maxUniqueColEntries(maxUniqueColEntries_)
181 , scratchLevel(scratchLevel_) {}
182
183 KOKKOS_INLINE_FUNCTION
184 void operator()(const typename Kokkos::TeamPolicy<execution_space>::member_type& thread) const {
185 auto rlid = thread.league_rank();
186 auto rowAinv = lclAinv.row(rlid);
187
188 // Loop over entries in row rlid of Ainv and collect all of A's column indices.
189 shared_lo_vector column_indices(thread.team_scratch(scratchLevel), maxUniqueColEntries);
190 local_ordinal_type numColEntries = 0;
191 for (local_ordinal_type ii = 0; ii < rowAinv.length; ++ii) {
192 auto i = rowAinv.colidx(ii);
193 auto rowA = lclA.rowConst(i);
194 for (local_ordinal_type jj = 0; jj < rowA.length; ++jj) {
195 auto j = rowA.colidx(jj);
196 column_indices(numColEntries) = j;
197 ++numColEntries;
198 }
199 }
200
201 // Get merged list of column indices.
202 local_ordinal_type numUniqeColEntries = 0;
203 local_ordinal_type diagOffset = 0;
204 {
205 // Sort
206 Kokkos::Experimental::sort_thread(thread, Kokkos::subview(column_indices, Kokkos::make_pair(0, numColEntries)));
207 // Merge
208 if (numColEntries > 0)
209 ++numUniqeColEntries;
210 local_ordinal_type pos = 0;
211 for (local_ordinal_type m = 1; m < numColEntries; ++m) {
212 if (column_indices(pos) != column_indices(m)) {
213 column_indices(pos + 1) = column_indices(m);
214 ++pos;
215 ++numUniqeColEntries;
216 if (column_indices(pos) == rlid)
217 diagOffset = pos;
218 }
219 }
220 }
221 // create a unique version of the column indices that has the correct length (as opposed
222 // to column_indices). Can we instead resize column_indices with MemoryUnmanaged?
223 // This is so that we can use binary search later on sorted list
224 shared_lo_vector uniqueColIndicies(thread.team_scratch(scratchLevel), numUniqeColEntries);
225 for (local_ordinal_type m = 0; m < numUniqeColEntries; ++m) {
226 uniqueColIndicies(m) = column_indices(m);
227 }
228
229 // Extract local part of A into a dense view.
230 shared_matrix localA(thread.team_scratch(scratchLevel), numUniqeColEntries, rowAinv.length);
231 KokkosBlas::SerialSet::invoke(impl_ATS::zero(), localA);
232
233 // Now fill localA.
234 for (local_ordinal_type ii = 0; ii < rowAinv.length; ++ii) {
235 auto i = rowAinv.colidx(ii);
236 auto rowA = lclA.rowConst(i);
237 for (local_ordinal_type jj = 0; jj < rowA.length; ++jj) {
238 auto j = rowA.colidx(jj);
239 auto v = rowA.value(jj);
240
241 // do binary search to find column in uniqueColIndices
242 auto it = KokkosKernels::lower_bound_thread(uniqueColIndicies, j);
243 localA(it, ii) = v;
244 }
245 }
246
247 shared_matrix ek(thread.team_scratch(scratchLevel), numUniqeColEntries, 1);
248 // set to zero, set diagonal entry to one
249 for (local_ordinal_type i = 0; i < numUniqeColEntries; ++i) {
250 ek(i, 0) = (i == diagOffset) ? impl_ATS::one() : impl_ATS::zero();
251 }
252
253 // QR solve
254 shared_vector tau(thread.team_scratch(scratchLevel), rowAinv.length);
255 shared_vector work(thread.team_scratch(scratchLevel), numUniqeColEntries);
256 // factorize localA = Q*R in-place
257 KokkosBatched::SerialQR<KokkosBatched::Algo::QR::Unblocked>::invoke(localA, tau, work);
258 // ek := Q^T ek
259 KokkosBatched::SerialApplyQ<KokkosBatched::Side::Left, KokkosBatched::Trans::Transpose, KokkosBatched::Algo::ApplyQ::Unblocked>::invoke(localA, tau, ek, work);
260 // ek[:rowLength] := R^{-1} ek[:rowLength]
261 auto sub_A = Kokkos::subview(localA, Kokkos::make_pair(0, rowAinv.length), Kokkos::ALL());
262 auto sub_ek = Kokkos::subview(ek, Kokkos::make_pair(0, rowAinv.length), 0);
263 KokkosBatched::SerialTrsv<KokkosBatched::Uplo::Upper, KokkosBatched::Trans::NoTranspose, KokkosBatched::Diag::NonUnit, KokkosBatched::Algo::Trsv::Unblocked>::invoke(impl_ATS::one(), sub_A, sub_ek);
264
265 // Set entries of Ainv.
266 for (local_ordinal_type i = 0; i < rowAinv.length; ++i) {
267 rowAinv.value(i) = sub_ek(i);
268 }
269 }
270};
271
272template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
273RCP<Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>>
274InverseApproximationFactory<Scalar, LocalOrdinal, GlobalOrdinal, Node>::GetSparseInverse(const RCP<Matrix>& Aorg, const RCP<const CrsGraph>& sparsityPattern) const {
275 using execution_space = typename Node::execution_space;
276
277 // construct the inverse matrix with the given sparsity pattern
278 RCP<Matrix> Ainv = MatrixFactory::Build(sparsityPattern);
279 Ainv->resumeFill();
280
281 // gather missing rows from other procs to generate an overlapping map
282 RCP<Import> rowImport = ImportFactory::Build(sparsityPattern->getRowMap(), sparsityPattern->getColMap());
283 RCP<Matrix> A = MatrixFactory::Build(Aorg, *rowImport);
284
285 auto maxRowEntriesAinv = Ainv->getLocalMaxNumRowEntries();
286 auto maxRowEntriesA = A->getLocalMaxNumRowEntries();
287 auto maxUniqueColEntries = maxRowEntriesAinv * maxRowEntriesA;
288 {
289 auto lclA = A->getLocalMatrixDevice();
290 auto lclAinv = Ainv->getLocalMatrixDevice();
291
292 Kokkos::TeamPolicy<execution_space> policy(lclAinv.numRows(), 1);
293
294 using spai_functor_type = LocalSPAIFunctor<decltype(lclAinv)>;
295 using shared_matrix = typename spai_functor_type::shared_matrix;
296 using shared_vector = typename spai_functor_type::shared_vector;
297 using shared_lo_vector = typename spai_functor_type::shared_lo_vector;
298
299 int size = shared_matrix::shmem_size(maxUniqueColEntries, maxRowEntriesAinv) + shared_matrix::shmem_size(maxUniqueColEntries, 1) + shared_vector::shmem_size(3 * maxUniqueColEntries) + shared_vector::shmem_size(maxRowEntriesAinv) + shared_lo_vector::shmem_size(maxUniqueColEntries);
300
301 int scratchLevel = -1;
302 if (size < policy.scratch_size_max(/*level=*/(int)0)) {
303 policy.set_scratch_size(/*level=*/(int)0, Kokkos::PerTeam(size));
304 scratchLevel = 0;
305 } else if (size < policy.scratch_size_max(/*level=*/(int)1)) {
306 policy.set_scratch_size(/*level=*/(int)1, Kokkos::PerTeam(size));
307 scratchLevel = 1;
308 } else
309 throw Exceptions::RuntimeError("Neither L0 scratch memory (max size " + std::to_string(policy.scratch_size_max((int)0)) +
310 "), nor L1 scratch memory (max size " + std::to_string(policy.scratch_size_max((int)1)) +
311 ") is large enough for requested allocation of size " + std::to_string(size));
312
313 LocalSPAIFunctor spaiFunctor(lclA, lclAinv, maxUniqueColEntries, scratchLevel);
314
315 Kokkos::parallel_for("MueLu::InverseFactory::LocalSpai", policy, spaiFunctor);
316 }
317
318 Ainv->fillComplete();
319
320 // Transpose needed to match published paper algorithms as the inverse is not symmetric
321 // However, non-transposed version seems to work better in row-oriented MinvA algorithm
322 // RCP<Matrix> actualSpai = Utilities::Transpose(*Ainv, true); // , label, Tparams);
323
324 return Ainv;
325}
326
327template <class local_matrix_type, typename global_ordinal_type>
328class LocalFSAIFunctor {
329 private:
330 using scalar_type = typename local_matrix_type::value_type;
331 using local_ordinal_type = typename local_matrix_type::ordinal_type;
332 using execution_space = typename local_matrix_type::execution_space;
333 using impl_scalar_type = typename KokkosKernels::ArithTraits<scalar_type>::val_type;
334 using impl_ATS = KokkosKernels::ArithTraits<impl_scalar_type>;
335 using device_type = typename local_matrix_type::device_type;
336 using local_map_type = Tpetra::Details::LocalMap<local_ordinal_type, global_ordinal_type, device_type>;
337
338 public:
339 using shared_matrix = Kokkos::View<impl_scalar_type**, typename execution_space::scratch_memory_space, Kokkos::MemoryUnmanaged>;
340 using shared_vector = Kokkos::View<impl_scalar_type*, typename execution_space::scratch_memory_space, Kokkos::MemoryUnmanaged>;
341 using shared_lo_vector = Kokkos::View<local_ordinal_type*, typename execution_space::scratch_memory_space, Kokkos::MemoryUnmanaged>;
342
343 private:
344 const local_matrix_type lclA;
345 local_matrix_type lclAinv;
346 local_map_type lclARowMap;
347 local_map_type lclAColMap;
348 local_map_type lclAinvRowMap;
349 local_map_type lclAinvColMap;
350 const int scratchLevel;
351
352 public:
353 LocalFSAIFunctor(const local_matrix_type& lclA_, local_matrix_type& lclAinv_, const local_map_type& lclARowMap_, const local_map_type& lclAColMap_,
354 const local_map_type& lclAinvRowMap_, const local_map_type& lclAinvColMap_, int scratchLevel_)
355 : lclA(lclA_)
356 , lclAinv(lclAinv_)
357 , lclARowMap(lclARowMap_)
358 , lclAColMap(lclAColMap_)
359 , lclAinvRowMap(lclAinvRowMap_)
360 , lclAinvColMap(lclAinvColMap_)
361 , scratchLevel(scratchLevel_) {}
362
363 KOKKOS_INLINE_FUNCTION
364 void operator()(const typename Kokkos::TeamPolicy<execution_space>::member_type& thread) const {
365 auto rlid = thread.league_rank();
366 auto rowAinv = lclAinv.row(rlid);
367
368 // matlab version of algorithm
369 // n = size(A,1); nzs = nnz(S);
370 // newrows = zeros(nzs,1); newcols = zeros(nzs,1); newvals= zeros(nzs,1);
371 // count = 0;
372 // for i=1:n,
373 // [~,subCols,~] = find(S(i,:));
374 // diagLocation = find(subCols == i);
375 // submat = A(subCols,subCols);
376 // subn = size(submat,1);
377 // if diagLocation ~= subn, fprintf('pattern not lower triangular?\n'); keyboard; end;
378 // identCol = zeros(subn,1); identCol(diagLocation) = 1;
379 // AinvFactorRow = submat\identCol;
380 // normalizedFactor = AinvFactorRow/sqrt(AinvFactorRow(diagLocation));
381 // newrows(count+1:count+subn) = i;
382 // newcols(count+1:count+subn) = subCols;
383 // newvals(count+1:count+subn) = normalizedFactor;
384 // count = count + subn;
385 // end;
386 // Lfactor = sparse(newrows,newcols,newvals,n,n);
387 //
388
389 auto A_rowGid = lclARowMap.getGlobalElement(rlid);
390
391 auto numRowEntries = rowAinv.length;
392 local_ordinal_type diagOffset = -1;
393 scalar_type diagValue = 0.0;
394 local_ordinal_type A_lclRowIndForDiag = -1;
395
396 // Loop over entries in row rlid of Ainv and collect all of A's column indices.
397 shared_lo_vector column_indices(thread.team_scratch(scratchLevel), numRowEntries);
398 local_ordinal_type numColEntries = rowAinv.length;
399 for (local_ordinal_type ii = 0; ii < rowAinv.length; ++ii) {
400 auto i = rowAinv.colidx(ii);
401 auto Ainv_colGid = lclAinvColMap.getGlobalElement(i); // for debugging
402 local_ordinal_type A_lclRowInd = lclARowMap.getLocalElement(Ainv_colGid);
403 local_ordinal_type A_lclColInd = lclAColMap.getLocalElement(Ainv_colGid);
404 column_indices(ii) = A_lclColInd;
405 if (A_rowGid == Ainv_colGid) {
406 A_lclRowIndForDiag = A_lclRowInd;
407 }
408 }
409#ifdef HAVE_MUELU_DEBUG // code must also be compiled with -DKokkos_ENABLE_DEBUG=ON
410 KOKKOS_ASSERT(A_lclRowIndForDiag != -1 && "MueLu::InverseApproximationFactory::GetSparseInverse: no diagonal entry found in A.");
411#endif
412
413 Kokkos::Experimental::sort_thread(thread, column_indices); // in order to apply binary search later
414 for (int kkk = 0; kkk < numColEntries; kkk++) {
415 if (column_indices(kkk) == A_lclRowIndForDiag) diagOffset = kkk;
416 }
417#ifdef HAVE_MUELU_DEBUG
418 KOKKOS_ASSERT(diagOffset != -1 && "MueLu::InverseApproximationFactory::GetSparseInverse: no diagonal entry offset found in A.");
419#endif
420
421 // Extract local part of A into a dense view.
422 shared_matrix localA(thread.team_scratch(scratchLevel), numRowEntries, rowAinv.length);
423 KokkosBlas::SerialSet::invoke(impl_ATS::zero(), localA);
424
425 // Now fill localA.
426 for (local_ordinal_type ii = 0; ii < rowAinv.length; ++ii) {
427 auto i = rowAinv.colidx(ii);
428 auto Ainv_colGid = lclAinvColMap.getGlobalElement(i); // for debugging
429 local_ordinal_type A_lclRowInd = lclARowMap.getLocalElement(Ainv_colGid);
430#ifdef HAVE_MUELU_DEBUG
431 KOKKOS_ASSERT(A_lclRowInd != -1 && "MueLu::InverseApproximationFactory: Column global ID in Ainv not found in A rowmap");
432#endif
433 auto rowA = lclA.rowConst(A_lclRowInd);
434
435 for (local_ordinal_type jj = 0; jj < rowA.length; ++jj) {
436 auto j = rowA.colidx(jj);
437 // do binary search to find column in column_indices, but first check that it is
438 // in lower triangular portion of matrix (because this might be faster?)
439 auto A_colGid = lclAColMap.getGlobalElement(j);
440 if (A_colGid <= A_rowGid) {
441 auto newIndex = KokkosKernels::lower_bound_thread(column_indices, j);
442 if ((newIndex < column_indices.extent(0)) && (column_indices(newIndex) == j))
443 localA(newIndex, ii) = rowA.value(jj);
444 }
445 }
446 }
447 shared_matrix ek(thread.team_scratch(scratchLevel), numRowEntries, 1);
448 // set to zero, set diagonal entry to one
449 for (local_ordinal_type i = 0; i < numRowEntries; ++i) {
450 ek(i, 0) = (i == diagOffset) ? impl_ATS::one() : impl_ATS::zero();
451 }
452
453 // QR solve
454 shared_vector tau(thread.team_scratch(scratchLevel), rowAinv.length);
455 shared_vector work(thread.team_scratch(scratchLevel), numRowEntries);
456 // factorize localA = Q*R in-place
457#define QRway
458#ifdef QRway
459 KokkosBatched::SerialQR<KokkosBatched::Algo::QR::Unblocked>::invoke(localA, tau, work);
460#else
461 KokkosBatched::SerialCholesky<KokkosBatched::Uplo::Lower, KokkosBatched::Algo::Cholesky::Unblocked>::invoke(localA); // use Cholesky
462#endif
463 // ek := Q^T ek
464#ifdef QRway
465 KokkosBatched::SerialApplyQ<KokkosBatched::Side::Left, KokkosBatched::Trans::Transpose, KokkosBatched::Algo::ApplyQ::Unblocked>::invoke(localA, tau, ek, work);
466 // ek[:rowLength] := R^{-1} ek[:rowLength]
467 auto sub_A = Kokkos::subview(localA, Kokkos::make_pair(0, rowAinv.length), Kokkos::ALL());
468#else
469 auto sub_A = Kokkos::subview(localA, Kokkos::make_pair(0, rowAinv.length), Kokkos::make_pair(0, rowAinv.length)); // use Cholesky
470#endif
471 auto sub_ek = Kokkos::subview(ek, Kokkos::make_pair(0, rowAinv.length), 0);
472#ifdef QRway
473 KokkosBatched::SerialTrsv<KokkosBatched::Uplo::Upper, KokkosBatched::Trans::NoTranspose, KokkosBatched::Diag::NonUnit, KokkosBatched::Algo::Trsv::Unblocked>::invoke(impl_ATS::one(), sub_A, sub_ek);
474#else
475 KokkosBatched::SerialTrsv<KokkosBatched::Uplo::Lower, KokkosBatched::Trans::NoTranspose, KokkosBatched::Diag::NonUnit, KokkosBatched::Algo::Trsv::Unblocked>::invoke(impl_ATS::one(), sub_A, sub_ek); // use Cholesky
476 KokkosBatched::SerialTrsv<KokkosBatched::Uplo::Lower, KokkosBatched::Trans::Transpose, KokkosBatched::Diag::NonUnit, KokkosBatched::Algo::Trsv::Unblocked>::invoke(impl_ATS::one(), sub_A, sub_ek); // use Cholesky
477#endif
478
479 // Set entries of Ainv.
480
481 diagValue = sub_ek(diagOffset);
482#ifdef HAVE_MUELU_DEBUG
483 KOKKOS_ASSERT(impl_ATS::real(diagValue) > 0.0 && "MueLu::InverseApproximationFactory::GetSparseInverse: non positive diagonal entry.");
484#endif
485 auto scale_factor = impl_ATS::one() / impl_ATS::sqrt(diagValue);
486 for (local_ordinal_type i = 0; i < rowAinv.length; ++i) {
487 typename KokkosKernels::ArithTraits<decltype(diagValue)>::val_type thevalue = sub_ek(i) * scale_factor;
488
489 if (thevalue == impl_ATS::zero()) thevalue = impl_ATS::eps();
490 rowAinv.value(i) = thevalue;
491 }
492 }
493};
494
495template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
496RCP<Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>>
497InverseApproximationFactory<Scalar, LocalOrdinal, GlobalOrdinal, Node>::GetFactoredSparseInverse(const RCP<Matrix>& Aorg, const RCP<const CrsGraph>& sparsityPattern) const {
498 using execution_space = typename Node::execution_space;
499
500 // construct the inverse matrix with factor the given sparsity pattern
501 RCP<Matrix> Ainv = MatrixFactory::Build(sparsityPattern);
502 Ainv->resumeFill();
503
504 // gather missing rows from other procs to generate an overlapping map
505 RCP<Import> rowImport = ImportFactory::Build(sparsityPattern->getRowMap(), sparsityPattern->getColMap());
506 RCP<Matrix> A = MatrixFactory::Build(Aorg, *rowImport);
507
508 auto maxRowEntriesAinv = Ainv->getLocalMaxNumRowEntries();
509 {
510 auto lclA = A->getLocalMatrixDevice();
511 auto lclAinv = Ainv->getLocalMatrixDevice();
512 auto lclARowmap = A->getRowMap()->getLocalMap();
513 auto lclAColmap = A->getColMap()->getLocalMap();
514 auto lclAinvRowmap = Ainv->getRowMap()->getLocalMap();
515 auto lclAinvColmap = Ainv->getColMap()->getLocalMap();
516 auto lclAorgRowmap = Aorg->getRowMap()->getLocalMap();
517
518 Kokkos::TeamPolicy<execution_space> policy(lclAinv.numRows(), 1);
519
520 using fsai_functor_type = LocalFSAIFunctor<decltype(lclAinv), GlobalOrdinal>;
521 using shared_matrix = typename fsai_functor_type::shared_matrix;
522 using shared_vector = typename fsai_functor_type::shared_vector;
523 using shared_lo_vector = typename fsai_functor_type::shared_lo_vector;
524
525 int size = shared_matrix::shmem_size(maxRowEntriesAinv, maxRowEntriesAinv) + shared_matrix::shmem_size(maxRowEntriesAinv, 1) + shared_vector::shmem_size(3 * maxRowEntriesAinv) + shared_vector::shmem_size(maxRowEntriesAinv) + shared_lo_vector::shmem_size(maxRowEntriesAinv);
526
527 int scratchLevel = -1;
528 if (size < policy.scratch_size_max(/*level=*/(int)0)) {
529 policy.set_scratch_size(/*level=*/(int)0, Kokkos::PerTeam(size));
530 scratchLevel = 0;
531 } else if (size < policy.scratch_size_max(/*level=*/(int)1)) {
532 policy.set_scratch_size(/*level=*/(int)1, Kokkos::PerTeam(size));
533 scratchLevel = 1;
534 } else
535 throw Exceptions::RuntimeError("Neither L0 scratch memory (max size " + std::to_string(policy.scratch_size_max((int)0)) +
536 "), nor L1 scratch memory (max size " + std::to_string(policy.scratch_size_max((int)1)) +
537 ") is large enough for requested allocation of size " + std::to_string(size));
538
539 LocalFSAIFunctor fsaiFunctor(lclA, lclAinv, lclARowmap, lclAColmap, lclAinvRowmap, lclAinvColmap, scratchLevel);
540
541 Kokkos::parallel_for("MueLu::InverseFactory::LocalSpai", policy, fsaiFunctor);
542 }
543
544 Ainv->fillComplete();
545
546 return Ainv;
547}
548
549#else
550
551template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
552RCP<Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>>
553InverseApproximationFactory<Scalar, LocalOrdinal, GlobalOrdinal, Node>::GetSparseInverse(const RCP<Matrix>& Aorg, const RCP<const CrsGraph>& sparsityPattern) const {
554 // construct the inverse matrix with the given sparsity pattern
555 RCP<Matrix> Ainv = MatrixFactory::Build(sparsityPattern);
556 Ainv->resumeFill();
557
558 // gather missing rows from other procs to generate an overlapping map
559 RCP<Import> rowImport = ImportFactory::Build(sparsityPattern->getRowMap(), sparsityPattern->getColMap());
560 RCP<Matrix> A = MatrixFactory::Build(Aorg, *rowImport);
561
562 // loop over all rows of the inverse sparsity pattern (this can be done in parallel)
563 for (size_t k = 0; k < sparsityPattern->getLocalNumRows(); k++) {
564 // 1. get column indices Ik of local row k
565 ArrayView<const LO> Ik;
566 sparsityPattern->getLocalRowView(k, Ik);
567
568 // 2. get all local A(Ik,:) rows
569 Array<ArrayView<const LO>> J(Ik.size());
570 Array<ArrayView<const SC>> Ak(Ik.size());
571 Array<LO> Jk;
572 for (LO i = 0; i < Ik.size(); i++) {
573 A->getLocalRowView(Ik[i], J[i], Ak[i]);
574 for (LO j = 0; j < J[i].size(); j++)
575 Jk.append(J[i][j]);
576 }
577 // set of unique column indices Jk
578 std::sort(Jk.begin(), Jk.end());
579 Jk.erase(std::unique(Jk.begin(), Jk.end()), Jk.end());
580 // create map
581 std::map<LO, LO> G;
582 for (LO i = 0; i < Jk.size(); i++) G.insert(std::pair<LO, LO>(Jk[i], i));
583
584 // 3. merge rows together
585 Teuchos::SerialDenseMatrix<LO, SC> localA(Jk.size(), Ik.size(), true);
586 for (LO i = 0; i < Ik.size(); i++) {
587 for (LO j = 0; j < J[i].size(); j++) {
588 localA(G.at(J[i][j]), i) = Ak[i][j];
589 }
590 }
591
592 // 4. get direction-vector
593 // diagonal needs an entry!
594 Teuchos::SerialDenseVector<LO, SC> ek(Jk.size(), true);
595 ek[std::find(Jk.begin(), Jk.end(), k) - Jk.begin()] = Teuchos::ScalarTraits<Scalar>::one();
596 ;
597
598 // 5. solve linear system for x
599 Teuchos::SerialDenseVector<LO, SC> localX(Ik.size());
600 Teuchos::SerialQRDenseSolver<LO, SC> qrSolver;
601 qrSolver.setMatrix(Teuchos::rcp(&localA, false));
602 qrSolver.setVectors(Teuchos::rcp(&localX, false), Teuchos::rcp(&ek, false));
603 const int err = qrSolver.solve();
604 TEUCHOS_TEST_FOR_EXCEPTION(err != 0, Exceptions::RuntimeError,
605 "MueLu::InverseApproximationFactory::GetSparseInverse: Error in serial QR solve.");
606
607 // 6. set calculated row into Ainv
608 ArrayView<const SC> Mk(localX.values(), localX.length());
609 Ainv->replaceLocalValues(k, Ik, Mk);
610 }
611 Ainv->fillComplete();
612
613 // Transpose needed to match published paper algorithms as the inverse is not symmetric
614 // However, non-transposed version seems to work better in row-oriented MinvA algorithm
615 // RCP<Matrix> actualSpai = Utilities::Transpose(*Ainv, true); // , label, Tparams);
616
617 return Ainv;
618}
619
620#endif
621
622} // namespace MueLu
623
624#endif /* MUELU_INVERSEAPPROXIMATIONFACTORY_DEF_HPP_ */
MueLu::DefaultGlobalOrdinal GlobalOrdinal
Exception throws to report errors in the internal logical of the program.
void Input(Level &level, const std::string &varName) const
T Get(Level &level, const std::string &varName) const
void Set(Level &level, const std::string &varName, const T &data) const
Timer to be used in factories. Similar to Monitor but with additional timers.
Factory for building the approximate inverse of a matrix.
void Build(Level &currentLevel) const
Build an object with this factory.
RCP< const ParameterList > GetValidParameterList() const
Return a const parameter list of valid parameters that setParameterList() will accept.
RCP< Matrix > GetSparseInverse(const RCP< Matrix > &A, const RCP< const CrsGraph > &sparsityPattern) const
Sparse inverse calculation method.
Class that holds all level-specific information.
static const RCP< const NoFactory > getRCP()
Static Get() functions.
virtual const Teuchos::ParameterList & GetParameterList() const
static RCP< Xpetra::CrsGraph< DefaultLocalOrdinal, DefaultGlobalOrdinal, DefaultNode > > GetThresholdedLowerTriangularGraph(const RCP< Matrix > &A, const Magnitude threshold, const bool symScaled=false)
static Teuchos::RCP< Vector > GetInverse(Teuchos::RCP< const Vector > v, Magnitude tol=Teuchos::ScalarTraits< Scalar >::eps() *100, Scalar valReplacement=Teuchos::ScalarTraits< Scalar >::zero())
static RCP< Matrix > GetThresholdedMatrix(const RCP< Matrix > &Ain, const Magnitude threshold, const bool keepDiagonal=true)
static RCP< Xpetra::CrsGraph< DefaultLocalOrdinal, DefaultGlobalOrdinal, DefaultNode > > GetThresholdedGraph(const RCP< Matrix > &A, const Magnitude threshold, const bool symScaled=false)
static Teuchos::RCP< Vector > GetLumpedMatrixDiagonal(Matrix const &A, const bool doReciprocal=false, Magnitude tol=Teuchos::ScalarTraits< Scalar >::magnitude(Teuchos::ScalarTraits< Scalar >::zero()), Scalar valReplacement=Teuchos::ScalarTraits< Scalar >::zero(), const bool replaceSingleEntryRowWithZero=false, const bool useAverageAbsDiagVal=false)
static RCP< Xpetra::Matrix< Scalar, LocalOrdinal, GlobalOrdinal, Node > > Transpose(Xpetra::Matrix< Scalar, LocalOrdinal, GlobalOrdinal, Node > &Op, bool optimizeTranspose=false, const std::string &label=std::string(), const Teuchos::RCP< Teuchos::ParameterList > &params=Teuchos::null)
Teuchos::FancyOStream & GetOStream(MsgType type, int thisProcRankOnly=0) const
Get an output stream for outputting the input message type.
bool IsPrint(MsgType type, int thisProcRankOnly=-1) const
Find out whether we need to print out information for a specific message type.
Namespace for MueLu classes and methods.
@ Statistics2
Print even more statistics.
@ Warnings
Print all warning messages.
@ Statistics1
Print more statistics.