MueLu Version of the Day
Loading...
Searching...
No Matches
MueLu_ClassicalMapFactory_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_CLASSICALMAPFACTORY_DEF_HPP_
11#define MUELU_CLASSICALMAPFACTORY_DEF_HPP_
12
13#include <Teuchos_Array.hpp>
14#include <Teuchos_ArrayRCP.hpp>
15
16#ifdef HAVE_MPI
17#include <Teuchos_DefaultMpiComm.hpp>
18#endif
19
20#include <Xpetra_Vector.hpp>
21#include <Xpetra_StridedMapFactory.hpp>
22#include <Xpetra_VectorFactory.hpp>
23#include <Xpetra_Import.hpp>
24#include <Xpetra_IO.hpp>
25
27#include "MueLu_Level.hpp"
28#include "MueLu_LWGraph.hpp"
29#include "MueLu_MasterList.hpp"
30#include "MueLu_Monitor.hpp"
31
32#ifdef HAVE_MUELU_ZOLTAN2
34#include <Zoltan2_XpetraCrsGraphAdapter.hpp>
35#include <Zoltan2_ColoringProblem.hpp>
36#include <Zoltan2_ColoringSolution.hpp>
37
38#endif
39
40#include "MueLu_LWGraph_kokkos.hpp"
41#include <KokkosGraph_Distance1ColorHandle.hpp>
42#include <KokkosGraph_Distance1Color.hpp>
43
44namespace MueLu {
45
46template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
48 RCP<ParameterList> validParamList = rcp(new ParameterList());
49#define SET_VALID_ENTRY(name) validParamList->setEntry(name, MasterList::getEntry(name))
50 SET_VALID_ENTRY("aggregation: deterministic");
51 SET_VALID_ENTRY("aggregation: coloring algorithm");
52 SET_VALID_ENTRY("aggregation: coloring: use color graph");
53#undef SET_VALID_ENTRY
54 validParamList->set<RCP<const FactoryBase> >("A", Teuchos::null, "Generating factory of the matrix A");
55 validParamList->set<RCP<const FactoryBase> >("UnAmalgamationInfo", Teuchos::null, "Generating factory of UnAmalgamationInfo");
56 validParamList->set<RCP<const FactoryBase> >("Graph", null, "Generating factory of the graph");
57 validParamList->set<RCP<const FactoryBase> >("Coloring Graph", null, "Generating factory of the graph");
58 validParamList->set<RCP<const FactoryBase> >("DofsPerNode", null, "Generating factory for variable \'DofsPerNode\', usually the same as for \'Graph\'");
59
60 return validParamList;
61}
62
63template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
65 Input(currentLevel, "A");
66 Input(currentLevel, "UnAmalgamationInfo");
67 Input(currentLevel, "Graph");
68
69 const ParameterList& pL = GetParameterList();
70 bool use_color_graph = pL.get<bool>("aggregation: coloring: use color graph");
71 if (use_color_graph)
72 Input(currentLevel, "Coloring Graph");
73}
74
75template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
77 FactoryMonitor m(*this, "Build", currentLevel);
78 const ParameterList& pL = GetParameterList();
79 RCP<const Matrix> A = Get<RCP<Matrix> >(currentLevel, "A");
80
81 RCP<const LWGraph> graph;
82 bool use_color_graph = pL.get<bool>("aggregation: coloring: use color graph");
83 if (use_color_graph)
84 graph = Get<RCP<LWGraph> >(currentLevel, "Coloring Graph");
85 else
86 graph = Get<RCP<LWGraph> >(currentLevel, "Graph");
87
88 /* ============================================================= */
89 /* Phase 1 : Compute an initial MIS */
90 /* ============================================================= */
91 ArrayRCP<LO> myColors;
92 LO numColors = 0;
93
94 RCP<LocalOrdinalVector> fc_splitting;
95 std::string coloringAlgo = pL.get<std::string>("aggregation: coloring algorithm");
96
97 // Switch to Zoltan2 if we're parallel and Tpetra (and not file)
98#ifdef HAVE_MUELU_ZOLTAN2
99 int numProcs = A->getRowMap()->getComm()->getSize();
100 if (coloringAlgo != "file" && numProcs > 1 && graph->GetDomainMap()->lib() == Xpetra::UseTpetra)
101 coloringAlgo = "Zoltan2";
102#endif
103
104 //#define CMS_DUMP
105#ifdef CMS_DUMP
106 {
107 int rank = graph->GetDomainMap()->getComm()->getRank();
108
109 printf("[%d,%d] graph local size = %dx%d\n", rank, currentLevel.GetLevelID(), (int)graph->GetDomainMap()->getLocalNumElements(), (int)graph->GetImportMap()->getLocalNumElements());
110
111 std::ofstream ofs(std::string("m_dropped_graph_") + std::to_string(currentLevel.GetLevelID()) + std::string("_") + std::to_string(rank) + std::string(".dat"), std::ofstream::out);
112 RCP<Teuchos::FancyOStream> fancy = Teuchos::fancyOStream(Teuchos::rcpFromRef(ofs));
113 graph->print(*fancy, Debug);
114 }
115 {
116 A->getRowMap()->getComm()->barrier();
117 }
118
119#endif
120
121 if (coloringAlgo == "file") {
122 // Read the CF splitting from disk
123 // NOTE: For interoperability reasons, this is dependent on the point_type enum not changing
124 std::string map_file = std::string("map_fcsplitting_") + std::to_string(currentLevel.GetLevelID()) + std::string(".m");
125 std::string color_file = std::string("fcsplitting_") + std::to_string(currentLevel.GetLevelID()) + std::string(".m");
126
127 FILE* mapfile = fopen(map_file.c_str(), "r");
128 using real_type = typename Teuchos::ScalarTraits<SC>::magnitudeType;
129 using RealValuedMultiVector = typename Xpetra::MultiVector<real_type, LO, GO, NO>;
130 RCP<RealValuedMultiVector> mv;
131
132 GetOStream(Statistics1) << "Reading FC splitting from " << color_file << ", using map file " << map_file << ". On rank " << A->getRowMap()->getComm()->getRank() << " local size is " << A->getRowMap()->getLocalNumElements() << std::endl;
133 if (mapfile) {
134 fclose(mapfile);
135 RCP<const Map> colorMap = Xpetra::IO<Scalar, LocalOrdinal, GlobalOrdinal, Node>::ReadMap(map_file, A->getRowMap()->lib(), A->getRowMap()->getComm());
136 TEUCHOS_TEST_FOR_EXCEPTION(!colorMap->isCompatible(*A->getRowMap()), std::invalid_argument, "Coloring on disk has incompatible map with A");
137
138 mv = Xpetra::IO<real_type, LocalOrdinal, GlobalOrdinal, Node>::ReadMultiVector(color_file, colorMap);
139 } else {
140 // Use A's rowmap and hope it matches
141 mv = Xpetra::IO<real_type, LocalOrdinal, GlobalOrdinal, Node>::ReadMultiVector(color_file, A->getRowMap());
142 }
143 TEUCHOS_TEST_FOR_EXCEPTION(mv.is_null(), std::invalid_argument, "Coloring on disk cannot be read");
144 fc_splitting = LocalOrdinalVectorFactory::Build(A->getRowMap());
145 TEUCHOS_TEST_FOR_EXCEPTION(mv->getLocalLength() != fc_splitting->getLocalLength(), std::invalid_argument, "Coloring map mismatch");
146
147 // Overlay the Dirichlet Points (and copy out the rest)
148 auto boundaryNodes = graph->GetBoundaryNodeMap();
149 ArrayRCP<const real_type> mv_data = mv->getData(0);
150 ArrayRCP<LO> fc_data = fc_splitting->getDataNonConst(0);
151 for (LO i = 0; i < (LO)fc_data.size(); i++) {
152 if (boundaryNodes[i])
153 fc_data[i] = DIRICHLET_PT;
154 else
155 fc_data[i] = Teuchos::as<LO>(mv_data[i]);
156 }
157 }
158#ifdef HAVE_MUELU_ZOLTAN2
159 else if (coloringAlgo.find("Zoltan2") != std::string::npos && graph->GetDomainMap()->lib() == Xpetra::UseTpetra) {
160 SubFactoryMonitor sfm(*this, "DistributedGraphColoring", currentLevel);
161 DoDistributedGraphColoring(graph, myColors, numColors);
162 }
163#endif
164 else if (coloringAlgo == "MIS" || graph->GetDomainMap()->lib() == Xpetra::UseTpetra) {
165 SubFactoryMonitor sfm(*this, "MIS", currentLevel);
166 TEUCHOS_TEST_FOR_EXCEPTION(A->getRowMap()->getComm()->getSize() != 1, std::invalid_argument, "MIS on more than 1 MPI rank is not supported");
167 DoMISNaive(*graph, myColors, numColors);
168 } else {
169 SubFactoryMonitor sfm(*this, "GraphColoring", currentLevel);
170 TEUCHOS_TEST_FOR_EXCEPTION(A->getRowMap()->getComm()->getSize() != 1, std::invalid_argument, "KokkosKernels graph coloring on more than 1 MPI rank is not supported");
171 DoGraphColoring(*graph, myColors, numColors);
172 }
173
174#ifdef CMS_DUMP
175 {
176 int rank = graph->GetDomainMap()->getComm()->getRank();
177
178 printf("[%d,%d] num colors %d\n", rank, currentLevel.GetLevelID(), numColors);
179
180 std::ofstream ofs(std::string("m_colors_") + std::to_string(currentLevel.GetLevelID()) + std::string("_") + std::to_string(rank) + std::string(".dat"), std::ofstream::out);
181 RCP<Teuchos::FancyOStream> fancy = Teuchos::fancyOStream(Teuchos::rcpFromRef(ofs));
182 *fancy << myColors();
183 }
184 {
185 A->getRowMap()->getComm()->barrier();
186 }
187
188#endif
189
190 /* ============================================================= */
191 /* Phase 2 : Mark the C-Points */
192 /* ============================================================= */
193 LO num_c_points = 0, num_d_points = 0, num_f_points = 0;
194 if (fc_splitting.is_null()) {
195 // We just have a coloring, so we need to generate a splitting
196 auto boundaryNodes = graph->GetBoundaryNodeMap();
197 fc_splitting = LocalOrdinalVectorFactory::Build(A->getRowMap());
198 ArrayRCP<LO> myPointType = fc_splitting->getDataNonConst(0);
199 for (LO i = 0; i < (LO)myColors.size(); i++) {
200 if (boundaryNodes[i]) {
201 myPointType[i] = DIRICHLET_PT;
202 num_d_points++;
203 } else if ((LO)myColors[i] == 1) {
204 myPointType[i] = C_PT;
205 num_c_points++;
206 } else
207 myPointType[i] = F_PT;
208 }
209 num_f_points = (LO)myColors.size() - num_d_points - num_c_points;
210 } else {
211 // If we read the splitting off disk, we just need to count
212 ArrayRCP<LO> myPointType = fc_splitting->getDataNonConst(0);
213
214 for (LO i = 0; i < (LO)myPointType.size(); i++) {
215 if (myPointType[i] == DIRICHLET_PT)
216 num_d_points++;
217 else if (myPointType[i] == C_PT)
218 num_c_points++;
219 }
220 num_f_points = (LO)myPointType.size() - num_d_points - num_c_points;
221 }
222
223 /* Output statistics on c/f/d points */
224 if (GetVerbLevel() & Statistics1) {
225 // NOTE: We batch the communication here
226 GO l_counts[] = {(GO)num_c_points, (GO)num_f_points, (GO)num_d_points};
227 GO g_counts[3];
228
229 RCP<const Teuchos::Comm<int> > comm = A->getRowMap()->getComm();
230 Teuchos::reduceAll(*comm, Teuchos::REDUCE_SUM, 3, l_counts, g_counts);
231 GetOStream(Statistics1) << "ClassicalMapFactory(" << coloringAlgo << "): C/F/D = " << g_counts[0] << "/" << g_counts[1] << "/" << g_counts[2] << std::endl;
232 }
233
234 /* Generate the Coarse map */
235 RCP<const Map> coarseMap;
236 {
237 SubFactoryMonitor sfm(*this, "Coarse Map", currentLevel);
238 GenerateCoarseMap(*A->getRowMap(), num_c_points, coarseMap);
239 }
240
241 Set(currentLevel, "FC Splitting", fc_splitting);
242 Set(currentLevel, "CoarseMap", coarseMap);
243}
244
245/* ************************************************************************* */
246template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
248 GenerateCoarseMap(const Map& fineMap, LO num_c_points, RCP<const Map>& coarseMap) const {
249 // FIXME: Assumes scalar PDE
250 std::vector<size_t> stridingInfo_(1);
251 stridingInfo_[0] = 1;
252 GO domainGIDOffset = 0;
253
254 coarseMap = StridedMapFactory::Build(fineMap.lib(),
255 Teuchos::OrdinalTraits<Xpetra::global_size_t>::invalid(),
256 num_c_points,
257 fineMap.getIndexBase(),
258 stridingInfo_,
259 fineMap.getComm(),
260 domainGIDOffset);
261}
262
263/* ************************************************************************* */
264template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
266 DoGraphColoring(const LWGraph& graph, ArrayRCP<LO>& myColors_out, LO& numColors) const {
267 const ParameterList& pL = GetParameterList();
268 using graph_t = typename LWGraph_kokkos::local_graph_type;
269 using KernelHandle = KokkosKernels::Experimental::
270 KokkosKernelsHandle<typename graph_t::row_map_type::value_type,
271 typename graph_t::entries_type::value_type,
272 typename graph_t::entries_type::value_type,
273 typename graph_t::device_type::execution_space,
274 typename graph_t::device_type::memory_space,
275 typename graph_t::device_type::memory_space>;
276 KernelHandle kh;
277
278 // Leave gc algorithm choice as the default
279 kh.create_graph_coloring_handle();
280
281 // Get the distance-1 graph coloring handle
282 auto coloringHandle = kh.get_graph_coloring_handle();
283
284 // Set the distance-1 coloring algorithm to use
285 if (pL.get<bool>("aggregation: deterministic") == true) {
286 coloringHandle->set_algorithm(KokkosGraph::COLORING_SERIAL);
287 if (IsPrint(Statistics1)) GetOStream(Statistics1) << " algorithm: serial" << std::endl;
288 } else if (pL.get<std::string>("aggregation: coloring algorithm") == "serial") {
289 coloringHandle->set_algorithm(KokkosGraph::COLORING_SERIAL);
290 if (IsPrint(Statistics1)) GetOStream(Statistics1) << " algorithm: serial" << std::endl;
291 } else if (pL.get<std::string>("aggregation: coloring algorithm") == "vertex based") {
292 coloringHandle->set_algorithm(KokkosGraph::COLORING_VB);
293 if (IsPrint(Statistics1)) GetOStream(Statistics1) << " algorithm: vertex based" << std::endl;
294 } else if (pL.get<std::string>("aggregation: coloring algorithm") == "vertex based bit array") {
295 coloringHandle->set_algorithm(KokkosGraph::COLORING_VBBIT);
296 if (IsPrint(Statistics1)) GetOStream(Statistics1) << " algorithm: vertex based bit array" << std::endl;
297 } else if (pL.get<std::string>("aggregation: coloring algorithm") == "vertex based color set") {
298 coloringHandle->set_algorithm(KokkosGraph::COLORING_VBCS);
299 if (IsPrint(Statistics1)) GetOStream(Statistics1) << " algorithm: vertex based color set" << std::endl;
300 } else if (pL.get<std::string>("aggregation: coloring algorithm") == "vertex based deterministic") {
301 coloringHandle->set_algorithm(KokkosGraph::COLORING_VBD);
302 if (IsPrint(Statistics1)) GetOStream(Statistics1) << " algorithm: vertex based deterministic" << std::endl;
303 } else if (pL.get<std::string>("aggregation: coloring algorithm") == "vertex based deterministic bit array") {
304 coloringHandle->set_algorithm(KokkosGraph::COLORING_VBDBIT);
305 if (IsPrint(Statistics1)) GetOStream(Statistics1) << " algorithm: vertex based deterministic bit array" << std::endl;
306 } else if (pL.get<std::string>("aggregation: coloring algorithm") == "edge based") {
307 coloringHandle->set_algorithm(KokkosGraph::COLORING_EB);
308 if (IsPrint(Statistics1)) GetOStream(Statistics1) << " algorithm: edge based" << std::endl;
309 } else {
310 TEUCHOS_TEST_FOR_EXCEPTION(true, std::invalid_argument, "Unrecognized distance 1 coloring algorithm");
311 }
312
313 // Create device views for graph rowptrs/colinds
314 size_t numRows = graph.GetNodeNumVertices();
315 // auto graphLWK = dynamic_cast<const LWGraph_kokkos*>(&graph);
316 auto graphLW = dynamic_cast<const LWGraph*>(&graph);
317 TEUCHOS_TEST_FOR_EXCEPTION(!graphLW, std::invalid_argument, "Graph is not a LWGraph object");
318 // Run d1 graph coloring
319 // Assume that the graph is symmetric so row map/entries and col map/entries are the same
320
321 // if (graphLWK) {
322 // KokkosGraph::Experimental::graph_color(&kh,
323 // numRows,
324 // numRows, // FIXME: This should be the number of columns
325 // graphLWK->getRowPtrs(),
326 // graphLWK->getEntries(),
327 // true);
328 // } else
329 if (graphLW) {
330 auto rowptrs = graphLW->getRowPtrs();
331 auto entries = graphLW->getEntries();
332 KokkosGraph::Experimental::graph_color(&kh,
333 numRows,
334 numRows, // FIXME: This should be the number of columns
335 rowptrs,
336 entries,
337 true);
338 }
339
340 // Extract the colors and store them in the aggregates
341 auto myColors_d = coloringHandle->get_vertex_colors();
342 numColors = static_cast<LO>(coloringHandle->get_num_colors());
343
344 // Copy back to host
345 auto myColors_h = Kokkos::create_mirror_view(myColors_d);
346 myColors_out.resize(myColors_h.size());
347 Kokkos::View<LO*, Kokkos::LayoutLeft, Kokkos::HostSpace> myColors_v(&myColors_out[0], myColors_h.size());
348 Kokkos::deep_copy(myColors_v, myColors_h);
349
350 // clean up coloring handle
351 kh.destroy_graph_coloring_handle();
352
353} // end DoGraphColoring
354
355/* ************************************************************************* */
356template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
358 DoMISNaive(const LWGraph& graph, ArrayRCP<LO>& myColors, LO& numColors) const {
359 // This is a fall-back routine for when we don't have Kokkos or when it isn't initialized
360 // We just do greedy MIS because this is easy to write.
361
362 LO LO_INVALID = Teuchos::OrdinalTraits<LO>::invalid();
363 LO MIS = Teuchos::ScalarTraits<LO>::one();
364
365 // FIXME: Not efficient
366 myColors.resize(0);
367 myColors.resize(graph.GetNodeNumVertices(), LO_INVALID);
368 auto boundaryNodes = graph.GetBoundaryNodeMap();
369 LO Nrows = (LO)graph.GetNodeNumVertices();
370
371 for (LO row = 0; row < Nrows; row++) {
372 if (boundaryNodes[row])
373 continue;
374 auto indices = graph.getNeighborVertices(row);
375 bool has_colored_neighbor = false;
376 for (LO j = 0; !has_colored_neighbor && j < (LO)indices.length; j++) {
377 // FIXME: This does not handle ghosting correctly
378 if (myColors[indices(j)] == MIS)
379 has_colored_neighbor = true;
380 }
381 if (!has_colored_neighbor)
382 myColors[row] = MIS;
383 }
384 numColors = 1;
385}
386
387/* ************************************************************************* */
388template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
390 DoDistributedGraphColoring(RCP<const LWGraph>& graph, ArrayRCP<LO>& myColors_out, LO& numColors) const {
391#ifdef HAVE_MUELU_ZOLTAN2
392 // const ParameterList& pL = GetParameterList();
393 Teuchos::ParameterList params;
394 params.set("color_choice", "FirstFit");
395 params.set("color_method", "D1");
396 // params.set("color_choice", colorMethod);
397 // params.set("color_method", colorAlg);
398 // params.set("verbose", verbose);
399 // params.set("serial_threshold",serialThreshold);
400 // params.set("recolor_degrees",recolorDegrees);
401
402 // Do the coloring via Zoltan2
403 using GraphAdapter = MueLuGraphBaseAdapter<LWGraph>;
404 GraphAdapter z_adapter(graph);
405
406 // We need to provide the MPI Comm, or else we wind up using the default (eep!)
407 Zoltan2::ColoringProblem<GraphAdapter> problem(&z_adapter, &params, graph->GetDomainMap()->getComm());
408 problem.solve();
409 Zoltan2::ColoringSolution<GraphAdapter>* soln = problem.getSolution();
410 ArrayRCP<int> colors = soln->getColorsRCP();
411 numColors = (LO)soln->getNumColors();
412
413 // Assign the Array RCP or Copy Out
414 // FIXME: This probably won't work if LO!=int
415 if (std::is_same<LO, int>::value)
416 myColors_out = colors;
417 else {
418 myColors_out.resize(colors.size());
419 for (LO i = 0; i < (LO)myColors_out.size(); i++)
420 myColors_out[i] = (LO)colors[i];
421 }
422
423 /*
424
425 printf("CMS: numColors = %d\ncolors = ",numColors);
426 for(int i=0;i<colors.size(); i++)
427 printf("%d ",colors[i]);
428 printf("\n");
429
430 */
431#endif // ifdef HAVE_MUELU_ZOLTAN2
432}
433
434} // namespace MueLu
435
436#endif /* MUELU_CLASSICALMAPFACTORY_DEF_HPP_ */
#define SET_VALID_ENTRY(name)
RCP< const ParameterList > GetValidParameterList() const override
Return a const parameter list of valid parameters that setParameterList() will accept.
virtual void GenerateCoarseMap(const Map &fineMap, LO num_c_points, Teuchos::RCP< const Map > &coarseMap) const
virtual void DoGraphColoring(const LWGraph &graph, Teuchos::ArrayRCP< LO > &myColors, LO &numColors) const
void DeclareInput(Level &currentLevel) const override
Specifies the data that this class needs, and the factories that generate that data.
virtual void DoDistributedGraphColoring(RCP< const LWGraph > &graph, Teuchos::ArrayRCP< LO > &myColors, LO &numColors) const
virtual void DoMISNaive(const LWGraph &graph, Teuchos::ArrayRCP< LO > &myColors, LO &numColors) const
void Build(Level &currentLevel) const override
Build an object with this factory.
Timer to be used in factories. Similar to Monitor but with additional timers.
KOKKOS_INLINE_FUNCTION size_type GetNodeNumVertices() const
Return number of graph vertices.
typename std::conditional< OnHost, typename local_graph_device_type::host_mirror_type, local_graph_device_type >::type local_graph_type
KOKKOS_INLINE_FUNCTION const boundary_nodes_type GetBoundaryNodeMap() const
Returns map with global ids of boundary nodes.
KOKKOS_INLINE_FUNCTION neighbor_vertices_type getNeighborVertices(LO i) const
Return the list of vertices adjacent to the vertex 'v'.
Lightweight MueLu representation of a compressed row storage graph.
Class that holds all level-specific information.
int GetLevelID() const
Return level number.
Timer to be used in factories. Similar to SubMonitor but adds a timer level by level.
Namespace for MueLu classes and methods.
@ Debug
Print additional debugging information.
@ Statistics1
Print more statistics.