Debian Codegraph @

packages/muelu/test/scaling/TAFCPerformance.cpp

raw
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 #include <cstdio>
11 #include <iomanip>
12 #include <iostream>
13 #include <unistd.h>
14
15 #include <Teuchos_XMLParameterListHelpers.hpp>
16 #include <Teuchos_StandardCatchMacros.hpp>
17
18 // Xpetra
19 #include <Xpetra_CrsMatrixFactory.hpp>
20 #include <Xpetra_MultiVectorFactory.hpp>
21 #include <Xpetra_ImportFactory.hpp>
22 #include <Xpetra_IO.hpp>
23
24 // Galeri
25 #include <Galeri_XpetraParameters.hpp>
26 #include <Galeri_XpetraProblemFactory.hpp>
27 #include <Galeri_XpetraUtils.hpp>
28 #include <Galeri_XpetraMaps.hpp>
29
30 #include <MueLu.hpp>
31
32 #include <MueLu_BaseClass.hpp>
33 #ifdef HAVE_MUELU_EXPLICIT_INSTANTIATION
34 #include <MueLu_ExplicitInstantiation.hpp>
35 #endif
36 #include <MueLu_Level.hpp>
37 #include <MueLu_MutuallyExclusiveTime.hpp>
38 #include <MueLu_ParameterListInterpreter.hpp>
39 #include <MueLu_Utilities.hpp>
40
41 #include <MueLu_CreateTpetraPreconditioner.hpp>
42 #ifdef HAVE_MUELU_EPETRA
43 #include <MueLu_CreateEpetraPreconditioner.hpp>
44 #include <EpetraExt_MMHelpers.h>
45 #include <EpetraExt_RowMatrixOut.h>
46 #endif
47
48 using Teuchos::RCP;
49 using Teuchos::rcp;
50 using Teuchos::TimeMonitor;
51
52 // =========================================================================
53 // =========================================================================
54 // =========================================================================
55 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
56 Teuchos::RCP<const Xpetra::Map<LocalOrdinal, GlobalOrdinal, Node> > build_map_for_transfer(const Teuchos::RCP<const Xpetra::Map<LocalOrdinal, GlobalOrdinal, Node> > oldMap) {
57 #include <MueLu_UseShortNames.hpp>
58 // 10 unknowns per proc except N-1: Assume Ids run from 0 to MaxGlobalIndex
59 int Nproc = oldMap->getComm()->getSize();
60 int MyPID = oldMap->getComm()->getRank();
61 int N = (int)oldMap->getGlobalNumElements();
62
63 Xpetra::UnderlyingLib lib = oldMap->lib();
64
65 if (Nproc == 1) return oldMap;
66
67 int start = MyPID == Nproc - 1 ? 0 : std::max(N - (MyPID + 1) * 10, 0);
68 int stop = std::max(N - MyPID * 10, 0);
69
70 Teuchos::Array<GlobalOrdinal> elems;
71 if (stop - start > 0) {
72 elems.resize(stop - start);
73 for (int i = 0; i < stop - start; i++)
74 elems[i] = start + i;
75 }
76
77 #if 0
78 printf("[%d] elems(%d) = ",MyPID,(int)elems.size());
79 for(int i=0; i<(int)elems.size(); i++)
80 printf("%d ",elems[i]);
81 printf("\n");
82 fflush(stdout);
83 #endif
84
85 return Xpetra::MapFactory<LO, GO, Node>::Build(lib, oldMap->getGlobalNumElements(), elems(), oldMap->getIndexBase(), oldMap->getComm());
86 }
87
88 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
89 Teuchos::RCP<const Xpetra::Map<LocalOrdinal, GlobalOrdinal, Node> > build_map_for_transfer_repartition(const Teuchos::RCP<const Xpetra::Map<LocalOrdinal, GlobalOrdinal, Node> > oldMap) {
90 #include <MueLu_UseShortNames.hpp>
91 // Turn P procs into ~P/9 procs
92 int Nproc = oldMap->getComm()->getSize();
93 int MyPID = oldMap->getComm()->getRank();
94 int N = (int)oldMap->getGlobalNumElements();
95
96 Xpetra::UnderlyingLib lib = oldMap->lib();
97
98 if (Nproc == 1) return oldMap;
99 int ideal_new_unknowns_per_proc = N / (Nproc / 9.0);
100
101 int start = ideal_new_unknowns_per_proc * MyPID < N ? ideal_new_unknowns_per_proc * MyPID : 0;
102 int stop = ideal_new_unknowns_per_proc * MyPID < N ? std::min(N, ideal_new_unknowns_per_proc * (MyPID + 1)) : 0;
103
104 Teuchos::Array<GlobalOrdinal> elems;
105 if (stop - start > 0) {
106 elems.resize(stop - start);
107 for (int i = 0; i < stop - start; i++)
108 elems[i] = start + i;
109 }
110
111 #if 0
112 printf("[%d] elems(%d) = ",MyPID,(int)elems.size());
113 for(int i=0; i<(int)elems.size(); i++)
114 printf("%d ",elems[i]);
115 printf("\n");
116 fflush(stdout);
117 #endif
118
119 int i_am_active = (elems.size() > 0);
120 int num_active = 0;
121 Teuchos::reduce(&i_am_active, &num_active, 1, Teuchos::REDUCE_SUM, 0, *oldMap->getComm());
122 if (MyPID == 0) printf("Repartitioning to %d/%d processors\n", num_active, Nproc);
123
124 return Xpetra::MapFactory<LO, GO, Node>::Build(lib, oldMap->getGlobalNumElements(), elems(), oldMap->getIndexBase(), oldMap->getComm());
125 }
126
127 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
128 Teuchos::RCP<const Xpetra::CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> > toXpetraCrs(Teuchos::RCP<Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> > &A) {
129 #include <MueLu_UseShortNames.hpp>
130 RCP<const CrsMatrixWrap> crswrapA = Teuchos::rcp_dynamic_cast<const CrsMatrixWrap>(A);
131 TEUCHOS_TEST_FOR_EXCEPTION(crswrapA == Teuchos::null, MueLu::Exceptions::BadCast,
132 "Cast from Xpetra::Matrix to Xpetra::CrsMatrixWrap failed");
133 RCP<CrsMatrix> crsA = crswrapA->getCrsMatrix();
134 TEUCHOS_TEST_FOR_EXCEPTION(crsA == Teuchos::null, std::runtime_error,
135 "Xpetra::CrsMatrixWrap doesn't have a CrsMatrix");
136 return crsA;
137 }
138
139 // =========================================================================
140 // =========================================================================
141 // =========================================================================
142 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
143 void TestTransferAndFillComplete(Teuchos::RCP<Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> > &A, Teuchos::RCP<Xpetra::Import<LocalOrdinal, GlobalOrdinal, Node> > &importer) {
144 #include <MueLu_UseShortNames.hpp>
145 // Xpetra::UnderlyingLib lib = A->getRowMap()->lib();
146 RCP<TimeMonitor> tm;
147
148 // It makes me sad to do this
149 Teuchos::RCP<const Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> > constA = Teuchos::rcp<const Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> >(&*A, false);
150
151 // Only makes sense in parallel
152 if (A->getRowMap()->getComm()->getSize() == 1) return;
153
154 // ==================
155 // Optimized Transfer
156 // ==================
157 {
158 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("OptimizedTransfer")));
159 RCP<Xpetra::CrsMatrix<Scalar, LO, GO, Node> > B = Xpetra::CrsMatrixFactory<Scalar, LO, GO, Node>::Build(toXpetraCrs(A), *importer);
160 }
161
162 A->getRowMap()->getComm()->barrier();
163
164 // ==================
165 // Naive Transfer
166 // ==================
167 {
168 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("NaiveTransfer")));
169 RCP<Xpetra::CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> > B = Xpetra::CrsMatrixFactory<Scalar, LO, GO, Node>::Build(importer->getTargetMap(), 0);
170 B->doImport(*toXpetraCrs(A), *importer, Xpetra::ADD);
171 B->fillComplete();
172 }
173 A->getRowMap()->getComm()->barrier();
174 }
175
176 // =========================================================================
177 // =========================================================================
178 // =========================================================================
179 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
180 int main_(Teuchos::CommandLineProcessor &clp, Xpetra::UnderlyingLib &lib, int argc, char *argv[]) {
181 #include <MueLu_UseShortNames.hpp>
182 using Teuchos::ArrayRCP;
183 using Teuchos::ParameterList;
184 using Teuchos::RCP;
185 using Teuchos::rcp;
186
187 typedef typename Teuchos::ScalarTraits<SC>::magnitudeType real_type;
188 typedef Xpetra::MultiVector<real_type, LO, GO, NO> RealValuedMultiVector;
189
190 // =========================================================================
191 // MPI initialization using Teuchos
192 // =========================================================================
193 RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm();
194
195 // =========================================================================
196 // Parameters initialization
197 // =========================================================================
198 GO nx = 200, ny = 200, nz = 10;
199 Galeri::Xpetra::Parameters<GO> galeriParameters(clp, nx, ny, nz, "Laplace2D"); // manage parameters of the test case
200 Xpetra::Parameters xpetraParameters(clp); // manage parameters of Xpetra
201
202 std::string xmlFileName = "import.xml";
203 clp.setOption("xml", &xmlFileName, "read parameters from a file");
204 bool printTimings = true;
205 clp.setOption("timings", "notimings", &printTimings, "print timings to screen");
206 std::string timingsFormat = "table-fixed";
207 clp.setOption("time-format", &timingsFormat, "timings format (table-fixed | table-scientific | yaml)");
208 int numImports = 100;
209 clp.setOption("numImport", &numImports, "#times to test");
210 std::string mapmode = "small";
211 clp.setOption("mapMode", &mapmode, "map to use ('small' or 'repartition')");
212
213 switch (clp.parse(argc, argv)) {
214 case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED: return EXIT_SUCCESS;
215 case Teuchos::CommandLineProcessor::PARSE_ERROR:
216 case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION: return EXIT_FAILURE;
217 case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL: break;
218 }
219
220 ParameterList paramList;
221 Teuchos::updateParametersFromXmlFileAndBroadcast(xmlFileName, Teuchos::Ptr<ParameterList>(&paramList), *comm);
222 bool isDriver = paramList.isSublist("Run1");
223 if (isDriver) {
224 // update galeriParameters with the values from the XML file
225 ParameterList &realParams = galeriParameters.GetParameterList();
226
227 for (ParameterList::ConstIterator it = realParams.begin(); it != realParams.end(); it++) {
228 const std::string &name = realParams.name(it);
229 if (paramList.isParameter(name))
230 realParams.setEntry(name, paramList.getEntry(name));
231 }
232 }
233
234 // Retrieve matrix parameters (they may have been changed on the command line)
235 // [for instance, if we changed matrix type from 2D to 3D we need to update nz]
236 ParameterList galeriList = galeriParameters.GetParameterList();
237
238 // =========================================================================
239 // Problem construction
240 // =========================================================================
241 std::ostringstream galeriStream;
242 comm->barrier();
243 RCP<TimeMonitor> globalTimeMonitor = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: S - Global Time")));
244 RCP<TimeMonitor> tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 1 - Matrix Build")));
245
246 RCP<Xpetra::Matrix<Scalar, LO, GO, Node> > A;
247 RCP<const Map> map;
248 RCP<RealValuedMultiVector> coordinates;
249 typedef typename RealValuedMultiVector::scalar_type Real;
250 RCP<MultiVector> nullspace;
251 galeriStream << "========================================================\n"
252 << xpetraParameters << galeriParameters;
253
254 // Galeri will attempt to create a square-as-possible distribution of subdomains di, e.g.,
255 // d1 d2 d3
256 // d4 d5 d6
257 // d7 d8 d9
258 // d10 d11 d12
259 // A perfect distribution is only possible when the #processors is a perfect square.
260 // This *will* result in "strip" distribution if the #processors is a prime number or if the factors are very different in
261 // size. For example, np=14 will give a 7-by-2 distribution.
262 // If you don't want Galeri to do this, specify mx or my on the galeriList.
263 std::string matrixType = galeriParameters.GetMatrixType();
264
265 // Create map and coordinates
266 // In the future, we hope to be able to first create a Galeri problem, and then request map and coordinates from it
267 // At the moment, however, things are fragile as we hope that the Problem uses same map and coordinates inside
268 if (matrixType == "Laplace1D") {
269 map = Galeri::Xpetra::CreateMap<LO, GO, Node>(xpetraParameters.GetLib(), "Cartesian1D", comm, galeriList);
270 coordinates = Galeri::Xpetra::Utils::CreateCartesianCoordinates<Real, LO, GO, Map, RealValuedMultiVector>("1D", map, galeriList);
271
272 } else if (matrixType == "Laplace2D" || matrixType == "Star2D" ||
273 matrixType == "BigStar2D" || matrixType == "Elasticity2D") {
274 map = Galeri::Xpetra::CreateMap<LO, GO, Node>(xpetraParameters.GetLib(), "Cartesian2D", comm, galeriList);
275 coordinates = Galeri::Xpetra::Utils::CreateCartesianCoordinates<Real, LO, GO, Map, RealValuedMultiVector>("2D", map, galeriList);
276
277 } else if (matrixType == "Laplace3D" || matrixType == "Brick3D" || matrixType == "Elasticity3D") {
278 map = Galeri::Xpetra::CreateMap<LO, GO, Node>(xpetraParameters.GetLib(), "Cartesian3D", comm, galeriList);
279 coordinates = Galeri::Xpetra::Utils::CreateCartesianCoordinates<Real, LO, GO, Map, RealValuedMultiVector>("3D", map, galeriList);
280 }
281
282 // Expand map to do multiple DOF per node for block problems
283 if (matrixType == "Elasticity2D")
284 map = Xpetra::MapFactory<LO, GO, Node>::Build(map, 2);
285 if (matrixType == "Elasticity3D")
286 map = Xpetra::MapFactory<LO, GO, Node>::Build(map, 3);
287
288 galeriStream << "Processor subdomains in x direction: " << galeriList.get<GO>("mx") << std::endl
289 << "Processor subdomains in y direction: " << galeriList.get<GO>("my") << std::endl
290 << "Processor subdomains in z direction: " << galeriList.get<GO>("mz") << std::endl
291 << "========================================================" << std::endl;
292
293 if (matrixType == "Elasticity2D" || matrixType == "Elasticity3D") {
294 // Our default test case for elasticity: all boundaries of a square/cube have Neumann b.c. except left which has Dirichlet
295 galeriList.set("right boundary", "Neumann");
296 galeriList.set("bottom boundary", "Neumann");
297 galeriList.set("top boundary", "Neumann");
298 galeriList.set("front boundary", "Neumann");
299 galeriList.set("back boundary", "Neumann");
300 }
301
302 RCP<Galeri::Xpetra::Problem<Map, CrsMatrixWrap, MultiVector> > Pr =
303 Galeri::Xpetra::BuildProblem<SC, LO, GO, Map, CrsMatrixWrap, MultiVector>(galeriParameters.GetMatrixType(), map, galeriList);
304 A = Pr->BuildMatrix();
305
306 comm->barrier();
307 tm = Teuchos::null;
308
309 galeriStream << "Galeri complete.\n========================================================" << std::endl;
310
311 int numReruns = 1;
312 if (paramList.isParameter("number of reruns"))
313 numReruns = paramList.get<int>("number of reruns");
314
315 const bool mustAlreadyExist = true;
316 for (int rerunCount = 1; rerunCount <= numReruns; rerunCount++) {
317 ParameterList mueluList, runList;
318 bool stop = false;
319 if (isDriver) {
320 runList = paramList.sublist("Run1", mustAlreadyExist);
321 mueluList = runList.sublist("MueLu", mustAlreadyExist);
322 } else {
323 mueluList = paramList;
324 stop = true;
325 }
326
327 int runCount = 1;
328 do {
329 int savedOut = -1;
330 FILE *openedOut = NULL;
331 if (isDriver) {
332 if (runList.isParameter("filename")) {
333 // Redirect all output into a filename We have to redirect all output,
334 // including printf's, therefore we cannot simply replace C++ cout
335 // buffers, and have to use heavy machinary (dup2)
336 std::string filename = runList.get<std::string>("filename");
337 if (numReruns > 1)
338 filename += "_run" + MueLu::toString(rerunCount);
339 filename += (lib == Xpetra::UseEpetra ? ".epetra" : ".tpetra");
340
341 savedOut = dup(STDOUT_FILENO);
342 openedOut = fopen(filename.c_str(), "w");
343 dup2(fileno(openedOut), STDOUT_FILENO);
344 }
345 }
346
347 // Instead of checking each time for rank, create a rank 0 stream
348 RCP<Teuchos::FancyOStream> fancy = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
349 Teuchos::FancyOStream &out = *fancy;
350 out.setOutputToRootOnly(0);
351 out << galeriStream.str();
352
353 // Build the target map for the importing
354 Teuchos::RCP<const Xpetra::Map<LocalOrdinal, GlobalOrdinal, Node> > importMap;
355 if (mapmode == "small")
356 importMap = build_map_for_transfer<Scalar, LO, GO, Node>(A->getRowMap());
357 else if (mapmode == "repartition")
358 importMap = build_map_for_transfer_repartition<Scalar, LO, GO, Node>(A->getRowMap());
359 else
360 throw std::runtime_error("Invalid map mode");
361
362 Teuchos::RCP<Xpetra::Import<LocalOrdinal, GlobalOrdinal, Node> > importer = Xpetra::ImportFactory<LO, GO, Node>::Build(A->getRowMap(), importMap);
363
364 for (int i = 0; i < numImports; i++) {
365 // =========================================================================
366 // Optimized transfer & fill complete loop
367 // =========================================================================
368 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 4 - TransferAndFillComplete")));
369 TestTransferAndFillComplete<Scalar, LO, GO, Node>(A, importer);
370 comm->barrier();
371 tm = Teuchos::null;
372 }
373
374 // Cleanup
375 globalTimeMonitor = Teuchos::null;
376
377 // =========================================================================
378 // Timing stuff
379 // =========================================================================
380 if (printTimings) {
381 RCP<ParameterList> reportParams = rcp(new ParameterList);
382 if (timingsFormat == "yaml") {
383 reportParams->set("Report format", "YAML"); // "Table" or "YAML"
384 reportParams->set("YAML style", "compact"); // "spacious" or "compact"
385 }
386 reportParams->set("How to merge timer sets", "Union");
387 reportParams->set("alwaysWriteLocal", false);
388 reportParams->set("writeGlobalStats", true);
389 reportParams->set("writeZeroTimers", false);
390 // FIXME: no "ignoreZeroTimers"
391
392 const std::string filter = "";
393
394 std::ios_base::fmtflags ff(out.flags());
395 if (timingsFormat == "table-fixed")
396 out << std::fixed;
397 else
398 out << std::scientific;
399 TimeMonitor::report(comm.ptr(), out, filter, reportParams);
400 out << std::setiosflags(ff);
401 }
402
403 TimeMonitor::clearCounters();
404
405 if (isDriver) {
406 if (openedOut != NULL) {
407 TEUCHOS_ASSERT(savedOut >= 0);
408 dup2(savedOut, STDOUT_FILENO);
409 fclose(openedOut);
410 openedOut = NULL;
411 }
412 try {
413 runList = paramList.sublist("Run" + MueLu::toString(++runCount), mustAlreadyExist);
414 mueluList = runList.sublist("MueLu", mustAlreadyExist);
415 } catch (Teuchos::Exceptions::InvalidParameterName &) {
416 stop = true;
417 }
418 }
419
420 } while (!stop);
421 }
422
423 return EXIT_SUCCESS;
424 }
425
426 //- -- --------------------------------------------------------
427 #define MUELU_AUTOMATIC_TEST_ETI_NAME main_
428 #include "MueLu_Test_ETI.hpp"
429
430 int main(int argc, char *argv[]) {
431 return Automatic_Test_ETI(argc, argv);
432 }