MueLu  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
MueLu_TentativePFactory_kokkos_def.hpp
Go to the documentation of this file.
1 // @HEADER
2 //
3 // ***********************************************************************
4 //
5 // MueLu: A package for multigrid based preconditioning
6 // Copyright 2012 Sandia Corporation
7 //
8 // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
9 // the U.S. Government retains certain rights in this software.
10 //
11 // Redistribution and use in source and binary forms, with or without
12 // modification, are permitted provided that the following conditions are
13 // met:
14 //
15 // 1. Redistributions of source code must retain the above copyright
16 // notice, this list of conditions and the following disclaimer.
17 //
18 // 2. Redistributions in binary form must reproduce the above copyright
19 // notice, this list of conditions and the following disclaimer in the
20 // documentation and/or other materials provided with the distribution.
21 //
22 // 3. Neither the name of the Corporation nor the names of the
23 // contributors may be used to endorse or promote products derived from
24 // this software without specific prior written permission.
25 //
26 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
27 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
30 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
31 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
32 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
33 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
34 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
35 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
36 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 //
38 // Questions? Contact
39 // Jonathan Hu (jhu@sandia.gov)
40 // Andrey Prokopenko (aprokop@sandia.gov)
41 // Ray Tuminaro (rstumin@sandia.gov)
42 //
43 // ***********************************************************************
44 //
45 // @HEADER
46 #ifndef MUELU_TENTATIVEPFACTORY_KOKKOS_DEF_HPP
47 #define MUELU_TENTATIVEPFACTORY_KOKKOS_DEF_HPP
48 
49 #ifdef HAVE_MUELU_KOKKOS_REFACTOR
50 
51 #include "Kokkos_UnorderedMap.hpp"
52 
54 
55 #include "MueLu_Aggregates_kokkos.hpp"
56 #include "MueLu_AmalgamationFactory_kokkos.hpp"
57 #include "MueLu_AmalgamationInfo_kokkos.hpp"
58 #include "MueLu_CoarseMapFactory_kokkos.hpp"
59 #include "MueLu_MasterList.hpp"
60 #include "MueLu_NullspaceFactory_kokkos.hpp"
61 #include "MueLu_PerfUtils.hpp"
62 #include "MueLu_Monitor.hpp"
63 #include "MueLu_Utilities_kokkos.hpp"
64 
65 namespace MueLu {
66 
67  namespace { // anonymous
68 
69  template<class LocalOrdinal, class View>
70  class ReduceMaxFunctor{
71  public:
72  ReduceMaxFunctor(View view) : view_(view) { }
73 
74  KOKKOS_INLINE_FUNCTION
75  void operator()(const LocalOrdinal &i, LocalOrdinal& vmax) const {
76  if (vmax < view_(i))
77  vmax = view_(i);
78  }
79 
80  KOKKOS_INLINE_FUNCTION
81  void join (volatile LocalOrdinal& dst, const volatile LocalOrdinal& src) const {
82  if (dst < src) {
83  dst = src;
84  }
85  }
86 
87  KOKKOS_INLINE_FUNCTION
88  void init (LocalOrdinal& dst) const {
89  dst = 0;
90  }
91  private:
92  View view_;
93  };
94 
95  // local QR decomposition
96  template<class LOType, class GOType, class SCType,class DeviceType, class NspType, class aggRowsType, class maxAggDofSizeType, class agg2RowMapLOType, class statusType, class rowsType, class rowsAuxType, class colsAuxType, class valsAuxType>
97  class LocalQRDecompFunctor {
98  private:
99  typedef LOType LO;
100  typedef GOType GO;
101  typedef SCType SC;
102 
103  typedef typename DeviceType::execution_space execution_space;
104  typedef Kokkos::ArithTraits<SC> ATS;
105  typedef typename ATS::magnitudeType Magnitude;
106 
109 
110  private:
111 
112  NspType fineNS;
113  NspType coarseNS;
114  aggRowsType aggRows;
115  maxAggDofSizeType maxAggDofSize; //< maximum number of dofs in aggregate (max size of aggregate * numDofsPerNode)
116  agg2RowMapLOType agg2RowMapLO;
117  statusType statusAtomic;
118  rowsType rows;
119  rowsAuxType rowsAux;
120  colsAuxType colsAux;
121  valsAuxType valsAux;
122  bool doQRStep;
123  public:
124  LocalQRDecompFunctor(NspType fineNS_, NspType coarseNS_, aggRowsType aggRows_, maxAggDofSizeType maxAggDofSize_, agg2RowMapLOType agg2RowMapLO_, statusType statusAtomic_, rowsType rows_, rowsAuxType rowsAux_, colsAuxType colsAux_, valsAuxType valsAux_, bool doQRStep_) :
125  fineNS(fineNS_),
126  coarseNS(coarseNS_),
127  aggRows(aggRows_),
128  maxAggDofSize(maxAggDofSize_),
129  agg2RowMapLO(agg2RowMapLO_),
130  statusAtomic(statusAtomic_),
131  rows(rows_),
132  rowsAux(rowsAux_),
133  colsAux(colsAux_),
134  valsAux(valsAux_),
135  doQRStep(doQRStep_)
136  { }
137 
138  KOKKOS_INLINE_FUNCTION
139  void operator() ( const typename Kokkos::TeamPolicy<execution_space>::member_type & thread, size_t& nnz) const {
140  auto agg = thread.league_rank();
141 
142  // size of aggregate: number of DOFs in aggregate
143  auto aggSize = aggRows(agg+1) - aggRows(agg);
144 
145  const SC one = ATS::one();
146  const SC two = one + one;
147  const SC zero = ATS::zero();
148  const auto zeroM = ATS::magnitude(zero);
149 
150  int m = aggSize;
151  int n = fineNS.extent(1);
152 
153  // calculate row offset for coarse nullspace
154  Xpetra::global_size_t offset = agg * n;
155 
156  if (doQRStep) {
157 
158  // Extract the piece of the nullspace corresponding to the aggregate
159  shared_matrix r(thread.team_shmem(), m, n); // A (initially), R (at the end)
160  for (int j = 0; j < n; j++)
161  for (int k = 0; k < m; k++)
162  r(k,j) = fineNS(agg2RowMapLO(aggRows(agg)+k),j);
163 #if 0
164  printf("A\n");
165  for (int i = 0; i < m; i++) {
166  for (int j = 0; j < n; j++)
167  printf(" %5.3lf ", r(i,j));
168  printf("\n");
169  }
170 #endif
171 
172  // Calculate QR decomposition (standard)
173  shared_matrix q(thread.team_shmem(), m, m); // Q
174  if (m >= n) {
175  bool isSingular = false;
176 
177  // Initialize Q^T
178  auto qt = q;
179  for (int i = 0; i < m; i++) {
180  for (int j = 0; j < m; j++)
181  qt(i,j) = zero;
182  qt(i,i) = one;
183  }
184 
185  for (int k = 0; k < n; k++) { // we ignore "n" instead of "n-1" to normalize
186  // FIXME_KOKKOS: use team
187  Magnitude s = zeroM, norm, norm_x;
188  for (int i = k+1; i < m; i++)
189  s += pow(ATS::magnitude(r(i,k)), 2);
190  norm = sqrt(pow(ATS::magnitude(r(k,k)), 2) + s);
191 
192  if (norm == zero) {
193  isSingular = true;
194  break;
195  }
196 
197  r(k,k) -= norm*one;
198 
199  norm_x = sqrt(pow(ATS::magnitude(r(k,k)), 2) + s);
200  if (norm_x == zeroM) {
201  // We have a single diagonal element in the column.
202  // No reflections required. Just need to restor r(k,k).
203  r(k,k) = norm*one;
204  continue;
205  }
206 
207  // FIXME_KOKKOS: use team
208  for (int i = k; i < m; i++)
209  r(i,k) /= norm_x;
210 
211  // Update R(k:m,k+1:n)
212  for (int j = k+1; j < n; j++) {
213  // FIXME_KOKKOS: use team in the loops
214  SC si = zero;
215  for (int i = k; i < m; i++)
216  si += r(i,k) * r(i,j);
217  for (int i = k; i < m; i++)
218  r(i,j) -= two*si * r(i,k);
219  }
220 
221  // Update Q^T (k:m,k:m)
222  for (int j = k; j < m; j++) {
223  // FIXME_KOKKOS: use team in the loops
224  SC si = zero;
225  for (int i = k; i < m; i++)
226  si += r(i,k) * qt(i,j);
227  for (int i = k; i < m; i++)
228  qt(i,j) -= two*si * r(i,k);
229  }
230 
231  // Fix R(k:m,k)
232  r(k,k) = norm*one;
233  for (int i = k+1; i < m; i++)
234  r(i,k) = zero;
235  }
236 
237 #if 0
238  // Q = (Q^T)^T
239  for (int i = 0; i < m; i++)
240  for (int j = 0; j < i; j++) {
241  SC tmp = qt(i,j);
242  qt(i,j) = qt(j,i);
243  qt(j,i) = tmp;
244  }
245 #endif
246 
247  // Build coarse nullspace using the upper triangular part of R
248  for (int j = 0; j < n; j++)
249  for (int k = 0; k <= j; k++)
250  coarseNS(offset+k,j) = r(k,j);
251 
252  if (isSingular) {
253  statusAtomic(1) = true;
254  return;
255  }
256 
257  } else {
258  // Special handling for m < n (i.e. single node aggregates in structural mechanics)
259 
260  // The local QR decomposition is not possible in the "overconstrained"
261  // case (i.e. number of columns in qr > number of rowsAux), which
262  // corresponds to #DOFs in Aggregate < n. For usual problems this
263  // is only possible for single node aggregates in structural mechanics.
264  // (Similar problems may arise in discontinuous Galerkin problems...)
265  // We bypass the QR decomposition and use an identity block in the
266  // tentative prolongator for the single node aggregate and transfer the
267  // corresponding fine level null space information 1-to-1 to the coarse
268  // level null space part.
269 
270  // NOTE: The resulting tentative prolongation operator has
271  // (m*DofsPerNode-n) zero columns leading to a singular
272  // coarse level operator A. To deal with that one has the following
273  // options:
274  // - Use the "RepairMainDiagonal" flag in the RAPFactory (default:
275  // false) to add some identity block to the diagonal of the zero rowsAux
276  // in the coarse level operator A, such that standard level smoothers
277  // can be used again.
278  // - Use special (projection-based) level smoothers, which can deal
279  // with singular matrices (very application specific)
280  // - Adapt the code below to avoid zero columns. However, we do not
281  // support a variable number of DOFs per node in MueLu/Xpetra which
282  // makes the implementation really hard.
283  //
284  // FIXME: do we need to check for singularity here somehow? Zero
285  // columns would be easy but linear dependency would require proper QR.
286 
287  // R = extended (by adding identity rowsAux) qr
288  for (int j = 0; j < n; j++)
289  for (int k = 0; k < n; k++)
290  if (k < m)
291  coarseNS(offset+k,j) = r(k,j);
292  else
293  coarseNS(offset+k,j) = (k == j ? one : zero);
294 
295  // Q = I (rectangular)
296  for (int i = 0; i < m; i++)
297  for (int j = 0; j < n; j++)
298  q(i,j) = (j == i ? one : zero);
299  }
300 
301  // Process each row in the local Q factor and fill helper arrays to assemble P
302  for (int j = 0; j < m; j++) {
303  LO localRow = agg2RowMapLO(aggRows(agg)+j);
304  size_t rowStart = rowsAux(localRow);
305  size_t lnnz = 0;
306  for (int k = 0; k < n; k++) {
307  // skip zeros
308  if (q(j,k) != zero) {
309  colsAux(rowStart+lnnz) = offset + k;
310  valsAux(rowStart+lnnz) = q(j,k);
311  lnnz++;
312  }
313  }
314  rows(localRow+1) = lnnz;
315  nnz += lnnz;
316  }
317 
318 #if 0
319  printf("R\n");
320  for (int i = 0; i < m; i++) {
321  for (int j = 0; j < n; j++)
322  printf(" %5.3lf ", coarseNS(i,j));
323  printf("\n");
324  }
325 
326  printf("Q\n");
327  for (int i = 0; i < aggSize; i++) {
328  for (int j = 0; j < aggSize; j++)
329  printf(" %5.3lf ", q(i,j));
330  printf("\n");
331  }
332 #endif
333  } else {
335  // "no-QR" option //
337  // Local Q factor is just the fine nullspace support over the current aggregate.
338  // Local R factor is the identity.
339  // TODO I have not implemented any special handling for aggregates that are too
340  // TODO small to locally support the nullspace, as is done in the standard QR
341  // TODO case above.
342 
343  for (int j = 0; j < m; j++) {
344  LO localRow = agg2RowMapLO(aggRows(agg)+j);
345  size_t rowStart = rowsAux(localRow);
346  size_t lnnz = 0;
347  for (int k = 0; k < n; k++) {
348  const SC qr_jk = fineNS(localRow,k);
349  // skip zeros
350  if (qr_jk != zero) {
351  colsAux(rowStart+lnnz) = offset + k;
352  valsAux(rowStart+lnnz) = qr_jk;
353  lnnz++;
354  }
355  }
356  rows(localRow+1) = lnnz;
357  nnz += lnnz;
358  }
359 
360  for (int j = 0; j < n; j++)
361  coarseNS(offset+j,j) = one;
362 
363  }
364 
365  }
366 
367  // amount of shared memory
368  size_t team_shmem_size( int /* team_size */ ) const {
369  if (doQRStep) {
370  int m = maxAggDofSize;
371  int n = fineNS.extent(1);
372  return shared_matrix::shmem_size(m, n) + // r
373  shared_matrix::shmem_size(m, m); // q
374  } else
375  return 0;
376  }
377  };
378 
379  } // namespace anonymous
380 
381  template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class DeviceType>
382  RCP<const ParameterList> TentativePFactory_kokkos<Scalar,LocalOrdinal,GlobalOrdinal,Kokkos::Compat::KokkosDeviceWrapperNode<DeviceType>>::GetValidParameterList() const {
383  RCP<ParameterList> validParamList = rcp(new ParameterList());
384 
385 #define SET_VALID_ENTRY(name) validParamList->setEntry(name, MasterList::getEntry(name))
386  SET_VALID_ENTRY("tentative: calculate qr");
387  SET_VALID_ENTRY("tentative: build coarse coordinates");
388 #undef SET_VALID_ENTRY
389 
390  validParamList->set< RCP<const FactoryBase> >("A", Teuchos::null, "Generating factory of the matrix A");
391  validParamList->set< RCP<const FactoryBase> >("Aggregates", Teuchos::null, "Generating factory of the aggregates");
392  validParamList->set< RCP<const FactoryBase> >("Nullspace", Teuchos::null, "Generating factory of the nullspace");
393  validParamList->set< RCP<const FactoryBase> >("Scaled Nullspace", Teuchos::null, "Generating factory of the scaled nullspace");
394  validParamList->set< RCP<const FactoryBase> >("UnAmalgamationInfo", Teuchos::null, "Generating factory of UnAmalgamationInfo");
395  validParamList->set< RCP<const FactoryBase> >("CoarseMap", Teuchos::null, "Generating factory of the coarse map");
396  validParamList->set< RCP<const FactoryBase> >("Coordinates", Teuchos::null, "Generating factory of the coordinates");
397 
398  // Make sure we don't recursively validate options for the matrixmatrix kernels
399  ParameterList norecurse;
400  norecurse.disableRecursiveValidation();
401  validParamList->set<ParameterList> ("matrixmatrix: kernel params", norecurse, "MatrixMatrix kernel parameters");
402 
403  return validParamList;
404  }
405 
406  template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class DeviceType>
407  void TentativePFactory_kokkos<Scalar,LocalOrdinal,GlobalOrdinal,Kokkos::Compat::KokkosDeviceWrapperNode<DeviceType>>::DeclareInput(Level& fineLevel, Level& /* coarseLevel */) const {
408 
409  const ParameterList& pL = GetParameterList();
410  // NOTE: This guy can only either be 'Nullspace' or 'Scaled Nullspace' or else the validator above will cause issues
411  std::string nspName = "Nullspace";
412  if(pL.isParameter("Nullspace name")) nspName = pL.get<std::string>("Nullspace name");
413 
414  Input(fineLevel, "A");
415  Input(fineLevel, "Aggregates");
416  Input(fineLevel, nspName);
417  Input(fineLevel, "UnAmalgamationInfo");
418  Input(fineLevel, "CoarseMap");
419  if( fineLevel.GetLevelID() == 0 &&
420  fineLevel.IsAvailable("Coordinates", NoFactory::get()) && // we have coordinates (provided by user app)
421  pL.get<bool>("tentative: build coarse coordinates") ) { // and we want coordinates on other levels
422  bTransferCoordinates_ = true; // then set the transfer coordinates flag to true
423  Input(fineLevel, "Coordinates");
424  } else if (bTransferCoordinates_) {
425  Input(fineLevel, "Coordinates");
426  }
427  }
428 
429  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class DeviceType>
430  void TentativePFactory_kokkos<Scalar,LocalOrdinal,GlobalOrdinal,Kokkos::Compat::KokkosDeviceWrapperNode<DeviceType>>::Build(Level& fineLevel, Level& coarseLevel) const {
431  return BuildP(fineLevel, coarseLevel);
432  }
433 
434  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class DeviceType>
435  void TentativePFactory_kokkos<Scalar,LocalOrdinal,GlobalOrdinal,Kokkos::Compat::KokkosDeviceWrapperNode<DeviceType>>::BuildP(Level& fineLevel, Level& coarseLevel) const {
436  FactoryMonitor m(*this, "Build", coarseLevel);
437 
438  typedef typename Teuchos::ScalarTraits<Scalar>::coordinateType coordinate_type;
439  typedef Xpetra::MultiVectorFactory<coordinate_type,LO,GO,NO> RealValuedMultiVectorFactory;
440  const ParameterList& pL = GetParameterList();
441  std::string nspName = "Nullspace";
442  if(pL.isParameter("Nullspace name")) nspName = pL.get<std::string>("Nullspace name");
443 
444  auto A = Get< RCP<Matrix> > (fineLevel, "A");
445  auto aggregates = Get< RCP<Aggregates_kokkos> > (fineLevel, "Aggregates");
446  auto amalgInfo = Get< RCP<AmalgamationInfo_kokkos> > (fineLevel, "UnAmalgamationInfo");
447  auto fineNullspace = Get< RCP<MultiVector> > (fineLevel, nspName);
448  auto coarseMap = Get< RCP<const Map> > (fineLevel, "CoarseMap");
449  RCP<RealValuedMultiVector> fineCoords;
450  if(bTransferCoordinates_) {
451  fineCoords = Get< RCP<RealValuedMultiVector> >(fineLevel, "Coordinates");
452  }
453 
454  RCP<Matrix> Ptentative;
455  RCP<MultiVector> coarseNullspace;
456  RCP<RealValuedMultiVector> coarseCoords;
457 
458  if(bTransferCoordinates_) {
459  ArrayView<const GO> elementAList = coarseMap->getNodeElementList();
460  GO indexBase = coarseMap->getIndexBase();
461 
462  LO blkSize = 1;
463  if (rcp_dynamic_cast<const StridedMap>(coarseMap) != Teuchos::null)
464  blkSize = rcp_dynamic_cast<const StridedMap>(coarseMap)->getFixedBlockSize();
465 
466  Array<GO> elementList;
467  ArrayView<const GO> elementListView;
468  if (blkSize == 1) {
469  // Scalar system
470  // No amalgamation required
471  elementListView = elementAList;
472 
473  } else {
474  auto numElements = elementAList.size() / blkSize;
475 
476  elementList.resize(numElements);
477 
478  // Amalgamate the map
479  for (LO i = 0; i < Teuchos::as<LO>(numElements); i++)
480  elementList[i] = (elementAList[i*blkSize]-indexBase)/blkSize + indexBase;
481 
482  elementListView = elementList;
483  }
484 
485  auto uniqueMap = fineCoords->getMap();
486  auto coarseCoordMap = MapFactory::Build(coarseMap->lib(), Teuchos::OrdinalTraits<Xpetra::global_size_t>::invalid(),
487  elementListView, indexBase, coarseMap->getComm());
488  coarseCoords = RealValuedMultiVectorFactory::Build(coarseCoordMap, fineCoords->getNumVectors());
489 
490  // Create overlapped fine coordinates to reduce global communication
491  RCP<RealValuedMultiVector> ghostedCoords = fineCoords;
492  if (aggregates->AggregatesCrossProcessors()) {
493  auto nonUniqueMap = aggregates->GetMap();
494  auto importer = ImportFactory::Build(uniqueMap, nonUniqueMap);
495 
496  ghostedCoords = RealValuedMultiVectorFactory::Build(nonUniqueMap, fineCoords->getNumVectors());
497  ghostedCoords->doImport(*fineCoords, *importer, Xpetra::INSERT);
498  }
499 
500  // The good new is that his graph has already been constructed for the
501  // TentativePFactory and was cached in Aggregates. So this is a no-op.
502  auto aggGraph = aggregates->GetGraph();
503  auto numAggs = aggGraph.numRows();
504 
505  auto fineCoordsView = fineCoords ->template getLocalView<DeviceType>();
506  auto coarseCoordsView = coarseCoords->template getLocalView<DeviceType>();
507 
508  // Fill in coarse coordinates
509  {
510  SubFactoryMonitor m2(*this, "AverageCoords", coarseLevel);
511 
512  const auto dim = fineCoords->getNumVectors();
513 
514  typename AppendTrait<decltype(fineCoordsView), Kokkos::RandomAccess>::type fineCoordsRandomView = fineCoordsView;
515  for (size_t j = 0; j < dim; j++) {
516  Kokkos::parallel_for("MueLu::TentativeP::BuildCoords", Kokkos::RangePolicy<local_ordinal_type, execution_space>(0, numAggs),
517  KOKKOS_LAMBDA(const LO i) {
518  // A row in this graph represents all node ids in the aggregate
519  // Therefore, averaging is very easy
520 
521  auto aggregate = aggGraph.rowConst(i);
522 
523  coordinate_type sum = 0.0; // do not use Scalar here (Stokhos)
524  for (size_t colID = 0; colID < static_cast<size_t>(aggregate.length); colID++)
525  sum += fineCoordsRandomView(aggregate(colID),j);
526 
527  coarseCoordsView(i,j) = sum / aggregate.length;
528  });
529  }
530  }
531  }
532 
533  if (!aggregates->AggregatesCrossProcessors())
534  BuildPuncoupled(coarseLevel, A, aggregates, amalgInfo, fineNullspace, coarseMap, Ptentative, coarseNullspace, coarseLevel.GetLevelID());
535  else
536  BuildPcoupled (A, aggregates, amalgInfo, fineNullspace, coarseMap, Ptentative, coarseNullspace);
537 
538  // If available, use striding information of fine level matrix A for range
539  // map and coarseMap as domain map; otherwise use plain range map of
540  // Ptent = plain range map of A for range map and coarseMap as domain map.
541  // NOTE:
542  // The latter is not really safe, since there is no striding information
543  // for the range map. This is not really a problem, since striding
544  // information is always available on the intermedium levels and the
545  // coarsest levels.
546  if (A->IsView("stridedMaps") == true)
547  Ptentative->CreateView("stridedMaps", A->getRowMap("stridedMaps"), coarseMap);
548  else
549  Ptentative->CreateView("stridedMaps", Ptentative->getRangeMap(), coarseMap);
550 
551  if(bTransferCoordinates_) {
552  Set(coarseLevel, "Coordinates", coarseCoords);
553  }
554  Set(coarseLevel, "Nullspace", coarseNullspace);
555  Set(coarseLevel, "P", Ptentative);
556 
557  if (IsPrint(Statistics1)) {
558  RCP<ParameterList> params = rcp(new ParameterList());
559  params->set("printLoadBalancingInfo", true);
560  GetOStream(Statistics1) << PerfUtils::PrintMatrixInfo(*Ptentative, "Ptent", params);
561  }
562  }
563 
564  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class DeviceType>
565  void TentativePFactory_kokkos<Scalar,LocalOrdinal,GlobalOrdinal,Kokkos::Compat::KokkosDeviceWrapperNode<DeviceType>>::
566  BuildPuncoupled(Level& coarseLevel, RCP<Matrix> A, RCP<Aggregates_kokkos> aggregates,
567  RCP<AmalgamationInfo_kokkos> amalgInfo, RCP<MultiVector> fineNullspace,
568  RCP<const Map> coarseMap, RCP<Matrix>& Ptentative,
569  RCP<MultiVector>& coarseNullspace, const int levelID) const {
570  auto rowMap = A->getRowMap();
571  auto colMap = A->getColMap();
572 
573  const size_t numRows = rowMap->getNodeNumElements();
574  const size_t NSDim = fineNullspace->getNumVectors();
575 
576  typedef Kokkos::ArithTraits<SC> ATS;
577  using impl_ATS = Kokkos::ArithTraits<typename ATS::val_type>;
578  const SC zero = ATS::zero(), one = ATS::one();
579 
580  const LO INVALID = Teuchos::OrdinalTraits<LO>::invalid();
581 
582  typename Aggregates_kokkos::local_graph_type aggGraph;
583  {
584  SubFactoryMonitor m2(*this, "Get Aggregates graph", coarseLevel);
585  aggGraph = aggregates->GetGraph();
586  }
587  auto aggRows = aggGraph.row_map;
588  auto aggCols = aggGraph.entries;
589 
590  // Aggregates map is based on the amalgamated column map
591  // We can skip global-to-local conversion if LIDs in row map are
592  // same as LIDs in column map
593  bool goodMap;
594  {
595  SubFactoryMonitor m2(*this, "Check good map", coarseLevel);
596  goodMap = isGoodMap(*rowMap, *colMap);
597  }
598  // FIXME_KOKKOS: need to proofread later code for bad maps
599  TEUCHOS_TEST_FOR_EXCEPTION(!goodMap, Exceptions::RuntimeError,
600  "MueLu: TentativePFactory_kokkos: for now works only with good maps "
601  "(i.e. \"matching\" row and column maps)");
602 
603  // STEP 1: do unamalgamation
604  // The non-kokkos version uses member functions from the AmalgamationInfo
605  // container class to unamalgamate the data. In contrast, the kokkos
606  // version of TentativePFactory does the unamalgamation here and only uses
607  // the data of the AmalgamationInfo container class
608 
609  // Extract information for unamalgamation
610  LO fullBlockSize, blockID, stridingOffset, stridedBlockSize;
611  GO indexBase;
612  amalgInfo->GetStridingInformation(fullBlockSize, blockID, stridingOffset, stridedBlockSize, indexBase);
613  GO globalOffset = amalgInfo->GlobalOffset();
614 
615  // Extract aggregation info (already in Kokkos host views)
616  auto procWinner = aggregates->GetProcWinner() ->template getLocalView<DeviceType>();
617  auto vertex2AggId = aggregates->GetVertex2AggId()->template getLocalView<DeviceType>();
618  const size_t numAggregates = aggregates->GetNumAggregates();
619 
620  int myPID = aggregates->GetMap()->getComm()->getRank();
621 
622  // Create Kokkos::View (on the device) to store the aggreate dof sizes
623  // Later used to get aggregate dof offsets
624  // NOTE: This zeros itself on construction
625  typedef typename Aggregates_kokkos::aggregates_sizes_type::non_const_type AggSizeType;
626  AggSizeType aggDofSizes;
627 
628  if (stridedBlockSize == 1) {
629  SubFactoryMonitor m2(*this, "Calc AggSizes", coarseLevel);
630 
631  // FIXME_KOKKOS: use ViewAllocateWithoutInitializing + set a single value
632  aggDofSizes = AggSizeType("agg_dof_sizes", numAggregates+1);
633 
634  auto sizesConst = aggregates->ComputeAggregateSizes();
635  Kokkos::deep_copy(Kokkos::subview(aggDofSizes, Kokkos::make_pair(static_cast<size_t>(1), numAggregates+1)), sizesConst);
636 
637  } else {
638  SubFactoryMonitor m2(*this, "Calc AggSizes", coarseLevel);
639 
640  // FIXME_KOKKOS: use ViewAllocateWithoutInitializing + set a single value
641  aggDofSizes = AggSizeType("agg_dof_sizes", numAggregates + 1);
642 
643  auto nodeMap = aggregates->GetMap()->getLocalMap();
644  auto dofMap = colMap->getLocalMap();
645 
646  Kokkos::parallel_for("MueLu:TentativePF:Build:compute_agg_sizes", range_type(0,numAggregates),
647  KOKKOS_LAMBDA(const LO agg) {
648  auto aggRowView = aggGraph.rowConst(agg);
649 
650  size_t size = 0;
651  for (LO colID = 0; colID < aggRowView.length; colID++) {
652  GO nodeGID = nodeMap.getGlobalElement(aggRowView(colID));
653 
654  for (LO k = 0; k < stridedBlockSize; k++) {
655  GO dofGID = (nodeGID - indexBase) * fullBlockSize + k + indexBase + globalOffset + stridingOffset;
656 
657  if (dofMap.getLocalElement(dofGID) != INVALID)
658  size++;
659  }
660  }
661  aggDofSizes(agg+1) = size;
662  });
663  }
664 
665  // Find maximum dof size for aggregates
666  // Later used to reserve enough scratch space for local QR decompositions
667  LO maxAggSize = 0;
668  ReduceMaxFunctor<LO,decltype(aggDofSizes)> reduceMax(aggDofSizes);
669  Kokkos::parallel_reduce("MueLu:TentativePF:Build:max_agg_size", range_type(0, aggDofSizes.extent(0)), reduceMax, maxAggSize);
670 
671  // parallel_scan (exclusive)
672  // The aggDofSizes View then contains the aggregate dof offsets
673  Kokkos::parallel_scan("MueLu:TentativePF:Build:aggregate_sizes:stage1_scan", range_type(0,numAggregates+1),
674  KOKKOS_LAMBDA(const LO i, LO& update, const bool& final_pass) {
675  update += aggDofSizes(i);
676  if (final_pass)
677  aggDofSizes(i) = update;
678  });
679 
680  // Create Kokkos::View on the device to store mapping
681  // between (local) aggregate id and row map ids (LIDs)
682  Kokkos::View<LO*, DeviceType> agg2RowMapLO(Kokkos::ViewAllocateWithoutInitializing("agg2row_map_LO"), numRows);
683  {
684  SubFactoryMonitor m2(*this, "Create Agg2RowMap", coarseLevel);
685 
686  AggSizeType aggOffsets(Kokkos::ViewAllocateWithoutInitializing("aggOffsets"), numAggregates);
687  Kokkos::deep_copy(aggOffsets, Kokkos::subview(aggDofSizes, Kokkos::make_pair(static_cast<size_t>(0), numAggregates)));
688 
689  Kokkos::parallel_for("MueLu:TentativePF:Build:createAgg2RowMap", range_type(0, vertex2AggId.extent(0)),
690  KOKKOS_LAMBDA(const LO lnode) {
691  if (procWinner(lnode, 0) == myPID) {
692  // No need for atomics, it's one-to-one
693  auto aggID = vertex2AggId(lnode,0);
694 
695  auto offset = Kokkos::atomic_fetch_add( &aggOffsets(aggID), stridedBlockSize );
696  // FIXME: I think this may be wrong
697  // We unconditionally add the whole block here. When we calculated
698  // aggDofSizes, we did the isLocalElement check. Something's fishy.
699  for (LO k = 0; k < stridedBlockSize; k++)
700  agg2RowMapLO(offset + k) = lnode*stridedBlockSize + k;
701  }
702  });
703  }
704 
705  // STEP 2: prepare local QR decomposition
706  // Reserve memory for tentative prolongation operator
707  coarseNullspace = MultiVectorFactory::Build(coarseMap, NSDim);
708 
709  // Pull out the nullspace vectors so that we can have random access (on the device)
710  auto fineNS = fineNullspace ->template getLocalView<DeviceType>();
711  auto coarseNS = coarseNullspace->template getLocalView<DeviceType>();
712 
713  size_t nnz = 0; // actual number of nnz
714 
715  typedef typename Xpetra::Matrix<SC,LO,GO,NO>::local_matrix_type local_matrix_type;
716  typedef typename local_matrix_type::row_map_type::non_const_type rows_type;
717  typedef typename local_matrix_type::index_type::non_const_type cols_type;
718  typedef typename local_matrix_type::values_type::non_const_type vals_type;
719 
720 
721  // Device View for status (error messages...)
722  typedef Kokkos::View<int[10], DeviceType> status_type;
723  status_type status("status");
724 
725  typename AppendTrait<decltype(fineNS), Kokkos::RandomAccess>::type fineNSRandom = fineNS;
726  typename AppendTrait<status_type, Kokkos::Atomic> ::type statusAtomic = status;
727 
728  const ParameterList& pL = GetParameterList();
729  const bool& doQRStep = pL.get<bool>("tentative: calculate qr");
730  if (!doQRStep) {
731  GetOStream(Runtime1) << "TentativePFactory : bypassing local QR phase" << std::endl;
732  if (NSDim>1)
733  GetOStream(Warnings0) << "TentativePFactor : for nontrivial nullspace, this may degrade performance" << std::endl;
734  }
735 
736  size_t nnzEstimate = numRows * NSDim;
737  rows_type rowsAux(Kokkos::ViewAllocateWithoutInitializing("Ptent_aux_rows"), numRows+1);
738  cols_type colsAux(Kokkos::ViewAllocateWithoutInitializing("Ptent_aux_cols"), nnzEstimate);
739  vals_type valsAux("Ptent_aux_vals", nnzEstimate);
740  rows_type rows("Ptent_rows", numRows+1);
741  {
742  // Stage 0: fill in views.
743  SubFactoryMonitor m2(*this, "Stage 0 (InitViews)", coarseLevel);
744 
745  // The main thing to notice is initialization of vals with INVALID. These
746  // values will later be used to compress the arrays
747  Kokkos::parallel_for("MueLu:TentativePF:BuildPuncoupled:for1", range_type(0, numRows+1),
748  KOKKOS_LAMBDA(const LO row) {
749  rowsAux(row) = row*NSDim;
750  });
751  Kokkos::parallel_for("MueLu:TentativePF:BuildUncoupled:for2", range_type(0, nnzEstimate),
752  KOKKOS_LAMBDA(const LO j) {
753  colsAux(j) = INVALID;
754  });
755  }
756 
757  if (NSDim == 1) {
758  // 1D is special, as it is the easiest. We don't even need to the QR,
759  // just normalize an array. Plus, no worries abot small aggregates. In
760  // addition, we do not worry about compression. It is unlikely that
761  // nullspace will have zeros. If it does, a prolongator row would be
762  // zero and we'll get singularity anyway.
763  SubFactoryMonitor m2(*this, "Stage 1 (LocalQR)", coarseLevel);
764 
765  // Set up team policy with numAggregates teams and one thread per team.
766  // Each team handles a slice of the data associated with one aggregate
767  // and performs a local QR decomposition (in this case real QR is
768  // unnecessary).
769  const Kokkos::TeamPolicy<execution_space> policy(numAggregates, 1);
770 
771  if (doQRStep) {
772  Kokkos::parallel_for("MueLu:TentativePF:BuildUncoupled:main_loop", policy,
773  KOKKOS_LAMBDA(const typename Kokkos::TeamPolicy<execution_space>::member_type &thread) {
774  auto agg = thread.league_rank();
775 
776  // size of the aggregate (number of DOFs in aggregate)
777  LO aggSize = aggRows(agg+1) - aggRows(agg);
778 
779  // Extract the piece of the nullspace corresponding to the aggregate, and
780  // put it in the flat array, "localQR" (in column major format) for the
781  // QR routine. Trivial in 1D.
782  auto norm = impl_ATS::magnitude(zero);
783 
784  // Calculate QR by hand
785  // FIXME: shouldn't there be stridedblock here?
786  // FIXME_KOKKOS: shouldn't there be stridedblock here?
787  for (decltype(aggSize) k = 0; k < aggSize; k++) {
788  auto dnorm = impl_ATS::magnitude(fineNSRandom(agg2RowMapLO(aggRows(agg)+k),0));
789  norm += dnorm*dnorm;
790  }
791  norm = sqrt(norm);
792 
793  if (norm == zero) {
794  // zero column; terminate the execution
795  statusAtomic(1) = true;
796  return;
797  }
798 
799  // R = norm
800  coarseNS(agg, 0) = norm;
801 
802  // Q = localQR(:,0)/norm
803  for (decltype(aggSize) k = 0; k < aggSize; k++) {
804  LO localRow = agg2RowMapLO(aggRows(agg)+k);
805  SC localVal = fineNSRandom(agg2RowMapLO(aggRows(agg)+k),0) / norm;
806 
807  rows(localRow+1) = 1;
808  colsAux(localRow) = agg;
809  valsAux(localRow) = localVal;
810 
811  }
812  });
813 
814  typename status_type::HostMirror statusHost = Kokkos::create_mirror_view(status);
815  Kokkos::deep_copy(statusHost, status);
816  for (decltype(statusHost.size()) i = 0; i < statusHost.size(); i++)
817  if (statusHost(i)) {
818  std::ostringstream oss;
819  oss << "MueLu::TentativePFactory::MakeTentative: ";
820  switch (i) {
821  case 0: oss << "!goodMap is not implemented"; break;
822  case 1: oss << "fine level NS part has a zero column"; break;
823  }
824  throw Exceptions::RuntimeError(oss.str());
825  }
826 
827  } else {
828  Kokkos::parallel_for("MueLu:TentativePF:BuildUncoupled:main_loop_noqr", policy,
829  KOKKOS_LAMBDA(const typename Kokkos::TeamPolicy<execution_space>::member_type &thread) {
830  auto agg = thread.league_rank();
831 
832  // size of the aggregate (number of DOFs in aggregate)
833  LO aggSize = aggRows(agg+1) - aggRows(agg);
834 
835  // R = norm
836  coarseNS(agg, 0) = one;
837 
838  // Q = localQR(:,0)/norm
839  for (decltype(aggSize) k = 0; k < aggSize; k++) {
840  LO localRow = agg2RowMapLO(aggRows(agg)+k);
841  SC localVal = fineNSRandom(agg2RowMapLO(aggRows(agg)+k),0);
842 
843  rows(localRow+1) = 1;
844  colsAux(localRow) = agg;
845  valsAux(localRow) = localVal;
846 
847  }
848  });
849  }
850 
851  Kokkos::parallel_reduce("MueLu:TentativeP:CountNNZ", range_type(0, numRows+1),
852  KOKKOS_LAMBDA(const LO i, size_t &nnz_count) {
853  nnz_count += rows(i);
854  }, nnz);
855 
856  } else { // NSdim > 1
857  // FIXME_KOKKOS: This code branch is completely unoptimized.
858  // Work to do:
859  // - Optimize QR decomposition
860  // - Remove INVALID usage similarly to CoalesceDropFactory_kokkos by
861  // packing new values in the beginning of each row
862  // We do use auxilary view in this case, so keep a second rows view for
863  // counting nonzeros in rows
864 
865  {
866  SubFactoryMonitor m2 = SubFactoryMonitor(*this, doQRStep ? "Stage 1 (LocalQR)" : "Stage 1 (Fill coarse nullspace and tentative P)", coarseLevel);
867  // Set up team policy with numAggregates teams and one thread per team.
868  // Each team handles a slice of the data associated with one aggregate
869  // and performs a local QR decomposition
870  const Kokkos::TeamPolicy<execution_space> policy(numAggregates,1); // numAggregates teams a 1 thread
871  LocalQRDecompFunctor<LocalOrdinal, GlobalOrdinal, Scalar, DeviceType, decltype(fineNSRandom),
872  decltype(aggDofSizes /*aggregate sizes in dofs*/), decltype(maxAggSize), decltype(agg2RowMapLO),
873  decltype(statusAtomic), decltype(rows), decltype(rowsAux), decltype(colsAux),
874  decltype(valsAux)>
875  localQRFunctor(fineNSRandom, coarseNS, aggDofSizes, maxAggSize, agg2RowMapLO, statusAtomic,
876  rows, rowsAux, colsAux, valsAux, doQRStep);
877  Kokkos::parallel_reduce("MueLu:TentativePF:BuildUncoupled:main_qr_loop", policy, localQRFunctor, nnz);
878  }
879 
880  typename status_type::HostMirror statusHost = Kokkos::create_mirror_view(status);
881  Kokkos::deep_copy(statusHost, status);
882  for (decltype(statusHost.size()) i = 0; i < statusHost.size(); i++)
883  if (statusHost(i)) {
884  std::ostringstream oss;
885  oss << "MueLu::TentativePFactory::MakeTentative: ";
886  switch(i) {
887  case 0: oss << "!goodMap is not implemented"; break;
888  case 1: oss << "fine level NS part has a zero column"; break;
889  }
890  throw Exceptions::RuntimeError(oss.str());
891  }
892  }
893 
894  // Compress the cols and vals by ignoring INVALID column entries that correspond
895  // to 0 in QR.
896 
897  // The real cols and vals are constructed using calculated (not estimated) nnz
898  cols_type cols;
899  vals_type vals;
900 
901  if (nnz != nnzEstimate) {
902  {
903  // Stage 2: compress the arrays
904  SubFactoryMonitor m2(*this, "Stage 2 (CompressRows)", coarseLevel);
905 
906  Kokkos::parallel_scan("MueLu:TentativePF:Build:compress_rows", range_type(0,numRows+1),
907  KOKKOS_LAMBDA(const LO i, LO& upd, const bool& final) {
908  upd += rows(i);
909  if (final)
910  rows(i) = upd;
911  });
912  }
913 
914  {
915  SubFactoryMonitor m2(*this, "Stage 2 (CompressCols)", coarseLevel);
916 
917  cols = cols_type("Ptent_cols", nnz);
918  vals = vals_type("Ptent_vals", nnz);
919 
920  // FIXME_KOKKOS: this can be spedup by moving correct cols and vals values
921  // to the beginning of rows. See CoalesceDropFactory_kokkos for
922  // example.
923  Kokkos::parallel_for("MueLu:TentativePF:Build:compress_cols_vals", range_type(0,numRows),
924  KOKKOS_LAMBDA(const LO i) {
925  LO rowStart = rows(i);
926 
927  size_t lnnz = 0;
928  for (auto j = rowsAux(i); j < rowsAux(i+1); j++)
929  if (colsAux(j) != INVALID) {
930  cols(rowStart+lnnz) = colsAux(j);
931  vals(rowStart+lnnz) = valsAux(j);
932  lnnz++;
933  }
934  });
935  }
936 
937  } else {
938  rows = rowsAux;
939  cols = colsAux;
940  vals = valsAux;
941  }
942 
943  GetOStream(Runtime1) << "TentativePFactory : aggregates do not cross process boundaries" << std::endl;
944 
945  {
946  // Stage 3: construct Xpetra::Matrix
947  SubFactoryMonitor m2(*this, "Stage 3 (LocalMatrix+FillComplete)", coarseLevel);
948 
949  local_matrix_type lclMatrix = local_matrix_type("A", numRows, coarseMap->getNodeNumElements(), nnz, vals, rows, cols);
950 
951  // Managing labels & constants for ESFC
952  RCP<ParameterList> FCparams;
953  if (pL.isSublist("matrixmatrix: kernel params"))
954  FCparams = rcp(new ParameterList(pL.sublist("matrixmatrix: kernel params")));
955  else
956  FCparams = rcp(new ParameterList);
957 
958  // By default, we don't need global constants for TentativeP
959  FCparams->set("compute global constants", FCparams->get("compute global constants", false));
960  FCparams->set("Timer Label", std::string("MueLu::TentativeP-") + toString(levelID));
961 
962  auto PtentCrs = CrsMatrixFactory::Build(lclMatrix, rowMap, coarseMap, coarseMap, A->getDomainMap());
963  Ptentative = rcp(new CrsMatrixWrap(PtentCrs));
964  }
965  }
966 
967  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class DeviceType>
968  void TentativePFactory_kokkos<Scalar,LocalOrdinal,GlobalOrdinal,Kokkos::Compat::KokkosDeviceWrapperNode<DeviceType>>::
969  BuildPcoupled(RCP<Matrix> /* A */, RCP<Aggregates_kokkos> /* aggregates */,
970  RCP<AmalgamationInfo_kokkos> /* amalgInfo */, RCP<MultiVector> /* fineNullspace */,
971  RCP<const Map> /* coarseMap */, RCP<Matrix>& /* Ptentative */,
972  RCP<MultiVector>& /* coarseNullspace */) const {
973  throw Exceptions::RuntimeError("MueLu: Construction of coupled tentative P is not implemented");
974  }
975 
976  template <class Scalar,class LocalOrdinal, class GlobalOrdinal, class DeviceType>
977  bool TentativePFactory_kokkos<Scalar,LocalOrdinal,GlobalOrdinal,Kokkos::Compat::KokkosDeviceWrapperNode<DeviceType>>::
978  isGoodMap(const Map& rowMap, const Map& colMap) const {
979  auto rowLocalMap = rowMap.getLocalMap();
980  auto colLocalMap = colMap.getLocalMap();
981 
982  const size_t numRows = rowLocalMap.getNodeNumElements();
983  const size_t numCols = colLocalMap.getNodeNumElements();
984 
985  if (numCols < numRows)
986  return false;
987 
988  size_t numDiff = 0;
989  Kokkos::parallel_reduce("MueLu:TentativePF:isGoodMap", range_type(0, numRows),
990  KOKKOS_LAMBDA(const LO i, size_t &diff) {
991  diff += (rowLocalMap.getGlobalElement(i) != colLocalMap.getGlobalElement(i));
992  }, numDiff);
993 
994  return (numDiff == 0);
995  }
996 
997 } //namespace MueLu
998 
999 #define MUELU_TENTATIVEPFACTORY_KOKKOS_SHORT
1000 #endif // HAVE_MUELU_KOKKOS_REFACTOR
1001 #endif // MUELU_TENTATIVEPFACTORY_KOKKOS_DEF_HPP
Important warning messages (one line)
MueLu::DefaultLocalOrdinal LocalOrdinal
void deep_copy(const View< DT, DP...> &dst, typename ViewTraits< DT, DP...>::const_value_type &value, typename std::enable_if< std::is_same< typename ViewTraits< DT, DP...>::specialize, void >::value >::type *=nullptr)
std::string toString(const T &what)
Little helper function to convert non-string types to strings.
KOKKOS_FORCEINLINE_FUNCTION constexpr pair< T1, T2 > make_pair(T1 x, T2 y)
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
Print more statistics.
KOKKOS_INLINE_FUNCTION Kokkos::complex< RealType > pow(const complex< RealType > &x, const RealType &e)
static const NoFactory * get()
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
MueLu::DefaultScalar Scalar
MueLu::DefaultGlobalOrdinal GlobalOrdinal
void parallel_reduce(const std::string &label, const PolicyType &policy, const FunctorType &functor, ReturnType &return_value, typename std::enable_if< Kokkos::Impl::is_execution_policy< PolicyType >::value >::type *=nullptr)
static std::string PrintMatrixInfo(const Matrix &A, const std::string &msgTag, RCP< const Teuchos::ParameterList > params=Teuchos::null)
KOKKOS_INLINE_FUNCTION Kokkos::complex< RealType > sqrt(const complex< RealType > &x)
void parallel_for(const ExecPolicy &policy, const FunctorType &functor, const std::string &str="", typename std::enable_if< Kokkos::Impl::is_execution_policy< ExecPolicy >::value >::type *=nullptr)
Description of what is happening (more verbose)
#define SET_VALID_ENTRY(name)