Debian Codegraph @

packages/muelu/test/scaling/MMKernelDriver.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 <stdlib.h> // for exit, EXIT_FA...
11 #include <Teuchos_StandardCatchMacros.hpp> // for TEUCHOS_STAND...
12 #include <iostream> // for endl, ostring...
13 #include <limits> // for numeric_limits
14 #include <random> // for mt19937, rand...
15 #include <stdexcept> // for runtime_error
16 #include <string> // for string
17 #include <fstream> // write CSV
18 #include "MueLu_ConfigDefs.hpp"
19 #include "KokkosKernels_Handle.hpp" // for KokkosKernels...
20 #include "KokkosSparse_spgemm_handle.hpp" // for StringToSPGEM...
21 #include "KokkosSparse_spgemm_numeric.hpp" // for spgemm_numeric
22 #include "KokkosSparse_spgemm_symbolic.hpp" // for spgemm_symbolic
23 #include "Teuchos_CommandLineProcessor.hpp" // for CommandLinePr...
24 #include "Teuchos_ENull.hpp" // for ENull::null
25 #include "Teuchos_FancyOStream.hpp" // for FancyOStream
26 #include "Teuchos_OrdinalTraits.hpp" // for OrdinalTraits
27 #include "Teuchos_RCP.hpp" // for rcp_const_cast
28 #include "Teuchos_RCPDecl.hpp" // for RCP, rcp
29 #include "Teuchos_ScalarTraitsDecl.hpp" // for ScalarTraits
30 #include "Tpetra_CrsMatrix_decl.hpp" // for CrsMatrix
31 #include "Tpetra_Import_decl.hpp" // for Import
32 #include <Tpetra_Import_Util2.hpp> // Import_Util::sortCrsEntries
33 #include "Tpetra_Map_decl.hpp" // for Map
34 #include <Xpetra_IO.hpp>
35 #include "Xpetra_BlockedMap.hpp" // for LO, GO, NO
36 #include "Xpetra_Map.hpp" // for UnderlyingLib
37 #include "Xpetra_Parameters.hpp" // for Parameters
38 #include "Xpetra_MatrixMatrix.hpp" //Xpetra SpGEMM
39 namespace Teuchos {
40 class ParameterList;
41 } // namespace Teuchos
42 namespace Teuchos {
43 class TimeMonitor;
44 } // namespace Teuchos
45 namespace Teuchos {
46 template <typename Ordinal>
47 class Comm;
48 } // namespace Teuchos
49 namespace Xpetra {
50 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
51 class Matrix;
52 } // namespace Xpetra
53
54 #ifdef HAVE_VTUNE
55 #include "ittnotify.h"
56 __itt_domain *vtune_domain_modLTG;
57 __itt_string_handle *vtune_task_modLTG_setup;
58 __itt_string_handle *vtune_task_modLTG_mult;
59 __itt_string_handle *vtune_task_modLTG_copy;
60 #endif
61
62 // MueLu
63 #include "MueLu.hpp"
64 #include "MueLu_TestHelpers.hpp"
65
66 #include <sys/types.h>
67 #include <unistd.h>
68
69 int getRssHWM() {
70 static const std::string mem_file = "/proc/self/status";
71 std::ifstream infile(mem_file);
72
73 std::string line;
74 while (std::getline(infile, line)) {
75 if (line.rfind("VmHWM", 0) == 0) {
76 // VmHWM: 1764 kB
77 std::stringstream ss(line);
78 std::string key;
79 int value;
80 std::string unit;
81 ss >> key >> value >> unit;
82 infile.close();
83 return (value);
84 }
85 }
86 infile.close();
87 return (-1);
88 }
89
90 #if USE_DESCRIPTIVE_STATS == 1
91 #include "descriptive_stats/descriptive_stats.hpp"
92 #include <iomanip>
93
94 // this will generate a pedantic warning
95 #define DescriptiveTime(x) ({ \
96 int rssStart = -1; \
97 int rssEnd = -1; \
98 if (trackRssHWM) { \
99 rssStart = getRssHWM(); \
100 } \
101 auto t0 = Time::now(); \
102 x; \
103 auto t1 = Time::now(); \
104 if (trackRssHWM) { \
105 rssEnd = getRssHWM(); \
106 mem_vector.push_back(static_cast<double>(rssEnd - rssStart)); \
107 } \
108 double_secs ds = t1 - t0; \
109 if (descStats) \
110 timing_vector.push_back(std::chrono::duration_cast<ns>(ds).count()); \
111 })
112
113 std::map<std::string, std::vector<double> > my_experiment_timings;
114
115 std::chrono::steady_clock::time_point ltg_core_start;
116 std::chrono::steady_clock::time_point ltg_sort_start;
117 std::chrono::steady_clock::time_point ltg_copy_start;
118 std::chrono::steady_clock::time_point ltg_mult_start;
119
120 std::chrono::steady_clock::time_point ltg_core_stop;
121 std::chrono::steady_clock::time_point ltg_sort_stop;
122 std::chrono::steady_clock::time_point ltg_copy_stop;
123 std::chrono::steady_clock::time_point ltg_mult_stop;
124
125 // MKL
126 std::chrono::steady_clock::time_point mkl_mult_start;
127 std::chrono::steady_clock::time_point mkl_copyin_start;
128 std::chrono::steady_clock::time_point mkl_copyout_start;
129 std::chrono::steady_clock::time_point mkl_sort_start;
130
131 std::chrono::steady_clock::time_point mkl_mult_stop;
132 std::chrono::steady_clock::time_point mkl_copyin_stop;
133 std::chrono::steady_clock::time_point mkl_copyout_stop;
134 std::chrono::steady_clock::time_point mkl_sort_stop;
135
136 // ViennaCL
137 std::chrono::steady_clock::time_point vcl_mult_start;
138 std::chrono::steady_clock::time_point vcl_mult_stop;
139
140 // KK D
141 std::chrono::steady_clock::time_point kk_dense_mult_start;
142 std::chrono::steady_clock::time_point kk_dense_copyout_start;
143
144 std::chrono::steady_clock::time_point kk_dense_mult_stop;
145 std::chrono::steady_clock::time_point kk_dense_copyout_stop;
146
147 // KK M
148 std::chrono::steady_clock::time_point kk_mem_mult_start;
149 std::chrono::steady_clock::time_point kk_mem_copyout_start;
150
151 std::chrono::steady_clock::time_point kk_mem_mult_stop;
152 std::chrono::steady_clock::time_point kk_mem_copyout_stop;
153
154 // KK D
155 std::chrono::steady_clock::time_point kk_def_mult_start;
156 std::chrono::steady_clock::time_point kk_def_copyout_start;
157
158 std::chrono::steady_clock::time_point kk_def_mult_stop;
159 std::chrono::steady_clock::time_point kk_def_copyout_stop;
160
161 // Xpetra
162 std::chrono::steady_clock::time_point xpetra_mult_start;
163 std::chrono::steady_clock::time_point xpetra_mult_stop;
164
165 #undef remove_pedantic_macro_warning_type
166 #else
167 #define DescriptiveTime(x) x
168 #endif
169
170 // =========================================================================
171 // Support Routines
172 // =========================================================================
173 template <class View1, class View2>
174 inline void copy_view_n(const int n, const View1 x1, View2 x2) {
175 Kokkos::parallel_for(
176 n, KOKKOS_LAMBDA(const size_t i) {
177 x2[i] = x1[i];
178 });
179 }
180
181 template <class View1, class View2>
182 inline void copy_view(const View1 x1, View2 x2) {
183 copy_view_n(x1.extent(0), x1, x2);
184 }
185
186 enum class Experiments { ViennaCL = 0,
187 MKL_SPMM,
188 KK_MEM,
189 KK_DENSE,
190 KK_DEFAULT,
191 LTG,
192 SERIAL,
193 XPETRA };
194
195 static inline std::string to_string(const Experiments &experiment_id) {
196 switch (experiment_id) {
197 case Experiments::ViennaCL:
198 return ("ViennaCL");
199 case Experiments::MKL_SPMM:
200 return ("MKL");
201 case Experiments::KK_MEM:
202 return ("KK_MEM");
203 case Experiments::KK_DENSE:
204 return ("KK_DENSE");
205 case Experiments::KK_DEFAULT:
206 return ("KK_DEFAULT");
207 case Experiments::LTG:
208 return ("LTG");
209 case Experiments::SERIAL:
210 return ("SERIAL");
211 case Experiments::XPETRA:
212 return ("XPETRA");
213 default:
214 return ("UNDEFINED");
215 }
216 }
217
218 // =========================================================================
219 // ViennaCL Testing
220 // =========================================================================
221 #ifdef HAVE_MUELU_VIENNACL
222 #define VIENNACL_WITH_OPENMP
223 #include "viennacl/compressed_matrix.hpp"
224 #include "viennacl/linalg/prod.hpp"
225 #include "viennacl/linalg/host_based/common.hpp"
226
227 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
228 void Multiply_ViennaCL(const Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> &A, const Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> &B, Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> &C) {
229 #include <MueLu_UseShortNames.hpp>
230 using Teuchos::RCP;
231 using Teuchos::rcp;
232 using Teuchos::TimeMonitor;
233
234 Xpetra::UnderlyingLib lib = A.getRowMap()->lib();
235 RCP<TimeMonitor> tm;
236
237 // NOTE: ViennaCL matrices use "unsigned int" for rowptr and colind and are templated on scalar type (yay); which means (for us) POD only.
238
239 if (lib == Xpetra::UseTpetra) {
240 typedef Tpetra::CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> crs_matrix_type;
241 typedef typename crs_matrix_type::local_matrix_type KCRS;
242 typedef typename KCRS::StaticCrsGraphType graph_t;
243 typedef typename graph_t::row_map_type::non_const_type lno_view_t;
244 typedef typename graph_t::row_map_type::const_type c_lno_view_t;
245 typedef typename graph_t::entries_type::non_const_type lno_nnz_view_t;
246 typedef typename graph_t::entries_type::const_type c_lno_nnz_view_t;
247 typedef typename KCRS::values_type::non_const_type scalar_view_t;
248 typedef typename Kokkos::View<unsigned int *, typename lno_nnz_view_t::array_layout, typename lno_nnz_view_t::device_type> vcl_size_t_type;
249
250 RCP<const crs_matrix_type> Au = toTpetra(rcp(&A, false));
251 RCP<const crs_matrix_type> Bu = toTpetra(rcp(&B, false));
252 RCP<const crs_matrix_type> Cu = toTpetra(rcp(&C, false));
253 RCP<crs_matrix_type> Cnc = Teuchos::rcp_const_cast<crs_matrix_type>(Cu);
254
255 const KCRS &Amat = Au->getLocalMatrixDevice();
256 const KCRS &Bmat = Bu->getLocalMatrixDevice();
257
258 using no_init_view = Kokkos::ViewAllocateWithoutInitializing;
259
260 c_lno_view_t Arowptr = Amat.graph.row_map, Browptr = Bmat.graph.row_map;
261 lno_view_t Crowptr(no_init_view("Crowptr"), C.getLocalNumRows() + 1);
262 c_lno_nnz_view_t Acolind = Amat.graph.entries, Bcolind = Bmat.graph.entries;
263 lno_nnz_view_t Ccolind;
264 const scalar_view_t Avals = Amat.values, Bvals = Bmat.values;
265 scalar_view_t Cvals;
266
267 // **********************************
268 // Copy in the data for ViennaCL
269
270 vcl_size_t_type ArowptrVCL(no_init_view("Arowptr"), Arowptr.extent(0));
271 vcl_size_t_type BrowptrVCL(no_init_view("Browptr"), Browptr.extent(0));
272
273 vcl_size_t_type AcolindVCL(no_init_view("Acolind"), Acolind.extent(0));
274 vcl_size_t_type BcolindVCL(no_init_view("Bcolind"), Bcolind.extent(0));
275
276 viennacl::compressed_matrix<Scalar> AVCL, BVCL;
277 {
278 Teuchos::TimeMonitor tm_copyin(*TimeMonitor::getNewTimer("MM ViennaCL: CopyIn"));
279 copy_view(Arowptr, ArowptrVCL);
280 copy_view(Browptr, BrowptrVCL);
281 copy_view(Acolind, AcolindVCL);
282 copy_view(Bcolind, BcolindVCL);
283
284 AVCL.set(ArowptrVCL.data(), AcolindVCL.data(), Avals.data(),
285 Au->getLocalNumRows(), Au->getLocalNumCols(), Au->getLocalNumEntries());
286 BVCL.set(BrowptrVCL.data(), BcolindVCL.data(), Bvals.data(),
287 Bu->getLocalNumRows(), Bu->getLocalNumCols(), Bu->getLocalNumEntries());
288 }
289 Au->getComm()->barrier();
290
291 viennacl::compressed_matrix<Scalar> CVCL;
292 // **********************************
293 // Multiply
294 {
295 Teuchos::TimeMonitor tm_mult(*TimeMonitor::getNewTimer("MM ViennaCL: Multiply"));
296 #ifdef USE_DESCRIPTIVE_STATS
297 vcl_mult_start = std::chrono::steady_clock::now();
298 #endif
299
300 CVCL = viennacl::linalg::prod(AVCL, BVCL);
301
302 #ifdef USE_DESCRIPTIVE_STATS
303 vcl_mult_stop = std::chrono::steady_clock::now();
304 #endif
305 }
306 KCRS::execution_space::fence();
307
308 // **********************************
309 // Copy out the data for ViennaCL
310 {
311 Teuchos::TimeMonitor tm_copy(*TimeMonitor::getNewTimer("MM ViennaCL: Copy Out"));
312 size_t cnnz = (size_t)CVCL.nnz();
313 Ccolind = lno_nnz_view_t(Kokkos::ViewAllocateWithoutInitializing("Ccolind"), cnnz);
314 Cvals = scalar_view_t(Kokkos::ViewAllocateWithoutInitializing("Cvals"), cnnz);
315 #ifdef VIENNACL_WITH_CUDA
316 const unsigned int *CrowptrVCL = viennacl::cuda_arg<unsigned int>(CVCL.handle1());
317 const unsigned int *CcolindVCL = viennacl::cuda_arg<unsigned int>(CVCL.handle2());
318 const Scalar *CvalsVCL = viennacl::cuda_arg<Scalar>(CVCL.handle());
319 #else
320 const unsigned int *CrowptrVCL = viennacl::linalg::host_based::detail::extract_raw_pointer<unsigned int>(CVCL.handle1());
321 const unsigned int *CcolindVCL = viennacl::linalg::host_based::detail::extract_raw_pointer<unsigned int>(CVCL.handle2());
322 const Scalar *CvalsVCL = viennacl::linalg::host_based::detail::extract_raw_pointer<Scalar>(CVCL.handle());
323 #endif
324
325 copy_view_n(Crowptr.extent(0), CrowptrVCL, Crowptr);
326 copy_view_n(cnnz, CcolindVCL, Ccolind);
327 copy_view_n(cnnz, CvalsVCL, Cvals);
328
329 // set values
330 {
331 // Because we're in serial...
332 Cnc->replaceColMap(Bu->getColMap());
333
334 Cnc->setAllValues(Crowptr,
335 Ccolind,
336 Cvals);
337 }
338 }
339 #ifdef USE_DESCRIPTIVE_STATS
340 {
341 std::chrono::duration<double> ds;
342
343 ds = vcl_mult_stop - vcl_mult_start;
344 my_experiment_timings["ViennaCL: Call"].push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(ds).count());
345 }
346 #endif
347
348 Au->getComm()->barrier();
349 }
350 }
351
352 #endif
353
354 // =========================================================================
355 // MKL Testing
356 // =========================================================================
357 #ifdef HAVE_MUELU_MKL
358 #include "mkl_spblas.h" // for mkl_sparse_de...
359 #include "mkl_types.h" // for MKL_INT
360 //#include "mkl.h"
361
362 #define MMKD_MKL_ERROR_CHECK(rc) \
363 { \
364 if (mkl_rc != SPARSE_STATUS_SUCCESS) { \
365 std::stringstream ss; \
366 switch (mkl_rc) { \
367 case SPARSE_STATUS_NOT_INITIALIZED: \
368 ss << "[ERROR] mkl::mkl_sparse_spmm: SPARSE_STATUS_NOT_INITIALIZED"; \
369 break; \
370 case SPARSE_STATUS_ALLOC_FAILED: \
371 ss << "[ERROR] mkl::mkl_sparse_spmm: SPARSE_STATUS_ALLOC_FAILED"; \
372 break; \
373 case SPARSE_STATUS_INVALID_VALUE: \
374 ss << "[ERROR] mkl::mkl_sparse_spmm: SPARSE_STATUS_INVALID_VALUE"; \
375 break; \
376 case SPARSE_STATUS_EXECUTION_FAILED: \
377 ss << "[ERROR] mkl::mkl_sparse_spmm: SPARSE_STATUS_EXECUTION_FAILED"; \
378 break; \
379 case SPARSE_STATUS_INTERNAL_ERROR: \
380 ss << "[ERROR] mkl::mkl_sparse_spmm: SPARSE_STATUS_INTERNAL_ERROR"; \
381 break; \
382 case SPARSE_STATUS_NOT_SUPPORTED: \
383 ss << "[ERROR] mkl::mkl_sparse_spmm: SPARSE_STATUS_NOT_SUPPORTED"; \
384 break; \
385 default: \
386 break; \
387 } \
388 std::cerr << ss.str() << std::endl; \
389 return; \
390 } \
391 }
392
393 // mkl_sparse_spmm
394 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
395 void Multiply_MKL_SPMM(const Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> &A, const Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> &B, Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> &C) {
396 #include <MueLu_UseShortNames.hpp>
397 using Teuchos::RCP;
398 using Teuchos::rcp;
399 using Teuchos::TimeMonitor;
400 // NOTE: MKL uses int as its columnn index type and the either double or float for its Scalar type
401 static constexpr bool sortCSR = false;
402
403 RCP<TimeMonitor> tm;
404 typedef Tpetra::CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> crs_matrix_type;
405 typedef typename crs_matrix_type::local_matrix_device_type KCRS;
406 typedef typename KCRS::StaticCrsGraphType graph_t;
407 typedef typename graph_t::row_map_type::non_const_type lno_view_t;
408 typedef typename graph_t::row_map_type::const_type c_lno_view_t;
409 typedef typename graph_t::entries_type::non_const_type lno_nnz_view_t;
410 typedef typename graph_t::entries_type::const_type c_lno_nnz_view_t;
411 typedef typename KCRS::values_type::non_const_type scalar_view_t;
412
413 typedef typename Kokkos::View<MKL_INT *, typename lno_nnz_view_t::array_layout, typename lno_nnz_view_t::device_type> mkl_int_type;
414
415 using no_init_view = Kokkos::ViewAllocateWithoutInitializing;
416
417 RCP<const crs_matrix_type> Au = toTpetra(rcp(&A, false));
418 RCP<const crs_matrix_type> Bu = toTpetra(rcp(&B, false));
419 RCP<const crs_matrix_type> Cu = toTpetra(rcp(&C, false));
420 RCP<crs_matrix_type> Cnc = Teuchos::rcp_const_cast<crs_matrix_type>(Cu);
421
422 const KCRS &Amat = Au->getLocalMatrixDevice();
423 const KCRS &Bmat = Bu->getLocalMatrixDevice();
424 if (A.getLocalNumRows() != C.getLocalNumRows()) throw std::runtime_error("C is not sized correctly");
425
426 c_lno_view_t Arowptr = Amat.graph.row_map, Browptr = Bmat.graph.row_map;
427 lno_view_t Crowptr(no_init_view("Crowptr"), C.getLocalNumRows() + 1);
428 c_lno_nnz_view_t Acolind = Amat.graph.entries, Bcolind = Bmat.graph.entries;
429 const scalar_view_t Avals = Amat.values, Bvals = Bmat.values;
430
431 sparse_matrix_t AMKL;
432 sparse_matrix_t BMKL;
433 sparse_matrix_t CMKL;
434 sparse_status_t mkl_rc;
435
436 mkl_int_type ArowptrMKL(no_init_view("Arowptr"), Arowptr.extent(0));
437 mkl_int_type BrowptrMKL(no_init_view("Browptr"), Browptr.extent(0));
438
439 mkl_int_type AcolindMKL(no_init_view("Acolind"), Acolind.extent(0));
440 mkl_int_type BcolindMKL(no_init_view("Bcolind"), Bcolind.extent(0));
441
442 {
443 // **********************************
444 // Copy in the data for MKL
445 Teuchos::TimeMonitor tm_copyin(*TimeMonitor::getNewTimer("MM MKL: CopyIn"));
446 #ifdef USE_DESCRIPTIVE_STATS
447 mkl_copyin_start = std::chrono::steady_clock::now();
448 #endif
449 copy_view(Arowptr, ArowptrMKL);
450 copy_view(Browptr, BrowptrMKL);
451 copy_view(Acolind, AcolindMKL);
452 copy_view(Bcolind, BcolindMKL);
453
454 if (std::is_same<Scalar, double>::value) {
455 mkl_rc = mkl_sparse_d_create_csr(&AMKL, SPARSE_INDEX_BASE_ZERO,
456 Au->getLocalNumRows(),
457 Au->getLocalNumCols(),
458 ArowptrMKL.data(),
459 ArowptrMKL.data() + 1,
460 AcolindMKL.data(),
461 (double *)Avals.data());
462 MMKD_MKL_ERROR_CHECK(mkl_rc);
463 mkl_rc = mkl_sparse_d_create_csr(&BMKL, SPARSE_INDEX_BASE_ZERO,
464 Bu->getLocalNumRows(),
465 Bu->getLocalNumCols(),
466 BrowptrMKL.data(),
467 BrowptrMKL.data() + 1,
468 BcolindMKL.data(),
469 (double *)Bvals.data());
470 MMKD_MKL_ERROR_CHECK(mkl_rc);
471 } else
472 throw std::runtime_error("MKL Type Mismatch");
473
474 #ifdef USE_DESCRIPTIVE_STATS
475 mkl_copyin_stop = std::chrono::steady_clock::now();
476 #endif
477 }
478 Au->getComm()->barrier();
479
480 // **********************************
481 // Multiply
482 {
483 Teuchos::TimeMonitor tm_mult(*TimeMonitor::getNewTimer("MM MKL: Multiply"));
484 #ifdef USE_DESCRIPTIVE_STATS
485 mkl_mult_start = std::chrono::steady_clock::now();
486 #endif
487 mkl_rc = mkl_sparse_spmm(SPARSE_OPERATION_NON_TRANSPOSE, AMKL, BMKL, &CMKL);
488 MMKD_MKL_ERROR_CHECK(mkl_rc);
489 #ifdef USE_DESCRIPTIVE_STATS
490 mkl_mult_stop = std::chrono::steady_clock::now();
491 #endif
492 // KCRS::execution_space::fence();
493 }
494 // **********************************
495
496 // Copy out the data for MKL
497 Teuchos::TimeMonitor tm_copy(*TimeMonitor::getNewTimer("MM MKL: Copy Out"));
498 #ifdef USE_DESCRIPTIVE_STATS
499 mkl_copyout_start = std::chrono::steady_clock::now();
500 #endif
501
502 sparse_index_base_t c_indexing;
503 MKL_INT c_rows, c_cols, *rows_start, *rows_end, *columns;
504 double *values;
505 mkl_rc = mkl_sparse_d_export_csr(CMKL, &c_indexing, &c_rows, &c_cols, &rows_start, &rows_end, &columns, &values);
506 MMKD_MKL_ERROR_CHECK(mkl_rc);
507 size_t cnnz = rows_end[c_rows - 1];
508 lno_nnz_view_t Ccolind = lno_nnz_view_t(Kokkos::ViewAllocateWithoutInitializing("Ccolind"), cnnz);
509 scalar_view_t Cvals = scalar_view_t(Kokkos::ViewAllocateWithoutInitializing("Cvals"), cnnz);
510 Kokkos::resize(Ccolind, cnnz);
511 Kokkos::resize(Cvals, cnnz);
512 if ((size_t)c_rows != A.getLocalNumRows() || (size_t)c_rows + 1 != Crowptr.extent(0)) throw std::runtime_error("C row size mismatch");
513 copy_view_n(c_rows, rows_start, Crowptr);
514 Crowptr(c_rows) = rows_end[c_rows - 1];
515 copy_view_n(cnnz, columns, Ccolind);
516 copy_view_n(cnnz, values, Cvals);
517
518 #ifdef USE_DESCRIPTIVE_STATS
519 mkl_copyout_stop = std::chrono::steady_clock::now();
520 #endif
521
522 if (sortCSR == true) {
523 #ifdef USE_DESCRIPTIVE_STATS
524 mkl_sort_start = std::chrono::steady_clock::now();
525 #endif
526
527 Tpetra::Import_Util::sortCrsEntries(Crowptr,
528 Ccolind,
529 Cvals);
530
531 #ifdef USE_DESCRIPTIVE_STATS
532 mkl_sort_stop = std::chrono::steady_clock::now();
533 #endif
534 }
535
536 // set values
537 {
538 // Because we're in serial...
539 Cnc->replaceColMap(Bu->getColMap());
540
541 Cnc->setAllValues(Crowptr,
542 Ccolind,
543 Cvals);
544 }
545
546 mkl_rc = mkl_sparse_destroy(AMKL);
547 MMKD_MKL_ERROR_CHECK(mkl_rc);
548 mkl_rc = mkl_sparse_destroy(BMKL);
549 MMKD_MKL_ERROR_CHECK(mkl_rc);
550 mkl_rc = mkl_sparse_destroy(CMKL);
551 MMKD_MKL_ERROR_CHECK(mkl_rc);
552
553 #ifdef USE_DESCRIPTIVE_STATS
554 {
555 std::chrono::duration<double> ds;
556
557 ds = mkl_mult_stop - mkl_mult_start;
558 my_experiment_timings["MKL: Call"].push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(ds).count());
559
560 ds = mkl_copyin_stop - mkl_copyin_start;
561 my_experiment_timings["MKL: CopyIn"].push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(ds).count());
562
563 ds = mkl_copyout_stop - mkl_copyout_start;
564 my_experiment_timings["MKL: CopyOut"].push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(ds).count());
565
566 ds = mkl_sort_stop - mkl_sort_start;
567 my_experiment_timings["MKL: Sort"].push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(ds).count());
568 }
569 #endif
570 }
571
572 #undef MMKD_MKL_ERROR_CHECK
573
574 #endif
575
576 // =========================================================================
577 // Kokkos Kernels Testing
578 // =========================================================================
579 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
580 void Multiply_KokkosKernels(const Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> &A, const Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> &B, Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> &C, std::string algorithm_name, int team_work_size) {
581 #include <MueLu_UseShortNames.hpp>
582 using Teuchos::RCP;
583 using Teuchos::rcp;
584 using Teuchos::TimeMonitor;
585
586 Xpetra::UnderlyingLib lib = A.getRowMap()->lib();
587
588 std::string prefix = std::string("MM KokkosKernels ") + algorithm_name + std::string(": ");
589
590 if (lib == Xpetra::UseTpetra) {
591 typedef Tpetra::CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> crs_matrix_type;
592 typedef typename crs_matrix_type::local_matrix_device_type KCRS;
593 typedef typename KCRS::StaticCrsGraphType graph_t;
594 typedef typename graph_t::row_map_type::non_const_type lno_view_t;
595 typedef typename graph_t::row_map_type::const_type c_lno_view_t;
596 typedef typename graph_t::entries_type::non_const_type lno_nnz_view_t;
597 typedef typename graph_t::entries_type::const_type c_lno_nnz_view_t;
598 typedef typename KCRS::values_type::non_const_type scalar_view_t;
599 typedef typename KCRS::device_type device_t;
600
601 RCP<const crs_matrix_type> Au = toTpetra(rcpFromRef(A));
602 RCP<const crs_matrix_type> Bu = toTpetra(rcpFromRef(B));
603 RCP<const crs_matrix_type> Cu = toTpetra(rcpFromRef(C));
604 RCP<crs_matrix_type> Cnc = Teuchos::rcp_const_cast<crs_matrix_type>(Cu);
605
606 const KCRS &Amat = Au->getLocalMatrixDevice();
607 const KCRS &Bmat = Bu->getLocalMatrixDevice();
608
609 c_lno_view_t Arowptr = Amat.graph.row_map, Browptr = Bmat.graph.row_map;
610 lno_view_t Crowptr("Crowptr", A.getLocalNumRows() + 1);
611 c_lno_nnz_view_t Acolind = Amat.graph.entries, Bcolind = Bmat.graph.entries;
612 const scalar_view_t Avals = Amat.values, Bvals = Bmat.values;
613 lno_nnz_view_t Ccolind;
614 scalar_view_t Cvals;
615
616 // KokkosKernelsHandle
617 typedef KokkosKernels::Experimental::KokkosKernelsHandle<
618 typename lno_view_t::const_value_type, typename lno_nnz_view_t::const_value_type, typename scalar_view_t::const_value_type,
619 typename device_t::execution_space, typename device_t::memory_space, typename device_t::memory_space>
620 KernelHandle;
621 KokkosSparse::SPGEMMAlgorithm alg_enum = KokkosSparse::StringToSPGEMMAlgorithm(algorithm_name);
622 typename KernelHandle::nnz_lno_t AnumRows = Au->getLocalNumRows();
623 typename KernelHandle::nnz_lno_t BnumRows = Bu->getLocalNumRows();
624 typename KernelHandle::nnz_lno_t BnumCols = Bu->getLocalNumCols();
625
626 // **********************************
627 // Multiply
628 {
629 Teuchos::TimeMonitor tm_mult(*TimeMonitor::getNewTimer(prefix + std::string("Multiply")));
630 #ifdef USE_DESCRIPTIVE_STATS
631 switch (alg_enum) {
632 case KokkosSparse::SPGEMMAlgorithm::SPGEMM_KK_DENSE:
633 kk_dense_mult_start = std::chrono::steady_clock::now();
634 break;
635 case KokkosSparse::SPGEMMAlgorithm::SPGEMM_KK_MEMORY:
636 kk_mem_mult_start = std::chrono::steady_clock::now();
637 break;
638 case KokkosSparse::SPGEMMAlgorithm::SPGEMM_KK:
639 kk_def_mult_start = std::chrono::steady_clock::now();
640 break;
641 default:
642 break;
643 }
644 #endif
645 KernelHandle kh;
646 kh.create_spgemm_handle(alg_enum);
647 kh.set_team_work_size(team_work_size);
648
649 KokkosSparse::Experimental::spgemm_symbolic(&kh, AnumRows, BnumRows, BnumCols,
650 Arowptr, Acolind, false,
651 Browptr, Bcolind, false,
652 Crowptr);
653
654 size_t c_nnz_size = kh.get_spgemm_handle()->get_c_nnz();
655 if (c_nnz_size) {
656 using no_init_view = Kokkos::ViewAllocateWithoutInitializing;
657 Ccolind = lno_nnz_view_t(no_init_view("entriesC"), c_nnz_size);
658 Cvals = scalar_view_t(no_init_view("valuesC"), c_nnz_size);
659 }
660 KokkosSparse::Experimental::spgemm_numeric(&kh, AnumRows, BnumRows, BnumCols,
661 Arowptr, Acolind, Avals, false,
662 Browptr, Bcolind, Bvals, false,
663 Crowptr, Ccolind, Cvals);
664 kh.destroy_spgemm_handle();
665 typename KCRS::execution_space().fence();
666
667 #ifdef USE_DESCRIPTIVE_STATS
668 switch (alg_enum) {
669 case KokkosSparse::SPGEMMAlgorithm::SPGEMM_KK_DENSE:
670 kk_dense_mult_stop = std::chrono::steady_clock::now();
671 break;
672 case KokkosSparse::SPGEMMAlgorithm::SPGEMM_KK_MEMORY:
673 kk_mem_mult_stop = std::chrono::steady_clock::now();
674 break;
675 case KokkosSparse::SPGEMMAlgorithm::SPGEMM_KK:
676 kk_def_mult_stop = std::chrono::steady_clock::now();
677 break;
678 default:
679 break;
680 }
681 #endif
682 } // scope time monitor mult
683 Au->getComm()->barrier();
684
685 // **********************************
686 // Copy out the data for KokkosKernels
687 {
688 Teuchos::TimeMonitor tm_copy(*TimeMonitor::getNewTimer(prefix + std::string("Copy Out")));
689 #ifdef USE_DESCRIPTIVE_STATS
690 switch (alg_enum) {
691 case KokkosSparse::SPGEMMAlgorithm::SPGEMM_KK_DENSE:
692 kk_dense_copyout_start = std::chrono::steady_clock::now();
693 break;
694 case KokkosSparse::SPGEMMAlgorithm::SPGEMM_KK_MEMORY:
695 kk_mem_copyout_start = std::chrono::steady_clock::now();
696 break;
697 case KokkosSparse::SPGEMMAlgorithm::SPGEMM_KK:
698 kk_def_copyout_start = std::chrono::steady_clock::now();
699 break;
700 default:
701 break;
702 }
703 #endif
704 // Because we're in serial...
705 Cnc->replaceColMap(Bu->getColMap());
706 Cnc->setAllValues(Crowptr,
707 Ccolind,
708 Cvals);
709
710 #ifdef USE_DESCRIPTIVE_STATS
711 std::chrono::duration<double> ds;
712 switch (alg_enum) {
713 case KokkosSparse::SPGEMMAlgorithm::SPGEMM_KK_DENSE:
714 kk_dense_copyout_stop = std::chrono::steady_clock::now();
715
716 ds = kk_dense_mult_stop - kk_dense_mult_start;
717 my_experiment_timings["KK DENSE: Call"].push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(ds).count());
718
719 ds = kk_dense_copyout_stop - kk_dense_copyout_start;
720 my_experiment_timings["KK DENSE: CopyOut"].push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(ds).count());
721 break;
722 case KokkosSparse::SPGEMMAlgorithm::SPGEMM_KK_MEMORY:
723 kk_mem_copyout_stop = std::chrono::steady_clock::now();
724
725 ds = kk_mem_mult_stop - kk_mem_mult_start;
726 my_experiment_timings["KK MEM: Call"].push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(ds).count());
727
728 ds = kk_mem_copyout_stop - kk_mem_copyout_start;
729 my_experiment_timings["KK MEM: CopyOut"].push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(ds).count());
730 break;
731 case KokkosSparse::SPGEMMAlgorithm::SPGEMM_KK:
732 kk_def_copyout_stop = std::chrono::steady_clock::now();
733
734 ds = kk_def_mult_stop - kk_def_mult_start;
735 my_experiment_timings["KK DEFAULT: Call"].push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(ds).count());
736
737 ds = kk_def_copyout_stop - kk_def_copyout_start;
738 my_experiment_timings["KK DEFAULT: CopyOut"].push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(ds).count());
739 break;
740 default:
741 break;
742 }
743 #endif
744 } // scope for Teuchos time monitor
745 } // lib
746 }
747
748 // =========================================================================
749 // LTG Testing
750 // =========================================================================
751 #include "Tpetra_Import_Util2.hpp"
752 #include "TpetraExt_MatrixMatrix.hpp"
753 #include "TpetraExt_MatrixMatrix_ExtraKernels_decl.hpp"
754 #include "TpetraExt_MatrixMatrix_ExtraKernels_def.hpp"
755
756 // The LTG kernel is only defined for the Kokkos OpenMP node, so
757 // its test must only be enabled for OpenMP
758 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
759 struct LTG_Tests {
760 static void Multiply_LTG(
761 const Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> &,
762 const Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> &,
763 Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> &) {}
764 };
765
766 #ifdef HAVE_TPETRA_INST_OPENMP
767
768 template <class Scalar, class LocalOrdinal, class GlobalOrdinal>
769 struct LTG_Tests<Scalar, LocalOrdinal, GlobalOrdinal, Tpetra::KokkosCompat::KokkosOpenMPWrapperNode> {
770 typedef Tpetra::KokkosCompat::KokkosOpenMPWrapperNode Node;
771 static void Multiply_LTG(const Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> &A,
772 const Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> &B,
773 Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> &C) {
774 #include <MueLu_UseShortNames.hpp>
775 using Teuchos::RCP;
776 using Teuchos::rcp;
777 using Teuchos::TimeMonitor;
778
779 Xpetra::UnderlyingLib lib = A.getRowMap()->lib();
780
781 if (lib == Xpetra::UseTpetra) {
782 typedef Tpetra::CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> crs_matrix_type;
783 typedef Tpetra::Import<LocalOrdinal, GlobalOrdinal, Node> import_type;
784 typedef typename crs_matrix_type::local_matrix_device_type KCRS;
785 typedef typename KCRS::device_type device_t;
786 typedef typename KCRS::StaticCrsGraphType graph_t;
787 typedef typename graph_t::row_map_type::non_const_type lno_view_t;
788 typedef typename graph_t::entries_type::non_const_type lno_nnz_view_t;
789 typedef typename KCRS::values_type::non_const_type scalar_view_t;
790 typedef Kokkos::View<LO *, typename lno_view_t::array_layout, typename lno_view_t::device_type> lo_view_t;
791 typedef Tpetra::Map<LO, GO, NO> map_type;
792 typedef typename map_type::local_map_type local_map_type;
793 typedef typename Node::execution_space execution_space;
794 typedef Kokkos::RangePolicy<execution_space, size_t> range_type;
795 LocalOrdinal LO_INVALID = Teuchos::OrdinalTraits<LO>::invalid();
796 RCP<const import_type> Cimport;
797 RCP<const crs_matrix_type> Au = toTpetra(rcp(&A, false));
798 RCP<const crs_matrix_type> Bu = toTpetra(rcp(&B, false));
799 RCP<const crs_matrix_type> Cu = toTpetra(rcp(&C, false));
800 RCP<crs_matrix_type> Cnc = Teuchos::rcp_const_cast<crs_matrix_type>(Cu);
801
802 using no_init_view = Kokkos::ViewAllocateWithoutInitializing;
803
804 // **********************************
805 // Copy in the data for LTG
806
807 Tpetra::CrsMatrixStruct<Scalar, LocalOrdinal, GlobalOrdinal, Node> Aview, Bview;
808 Aview.origMatrix = Au;
809 Aview.origRowMap = Au->getRowMap();
810 Aview.rowMap = Au->getRowMap();
811 Aview.colMap = Au->getColMap();
812 Aview.domainMap = Au->getDomainMap();
813 Aview.importColMap = Teuchos::null;
814
815 Bview.origMatrix = Bu;
816 Bview.origRowMap = Bu->getRowMap();
817 Bview.rowMap = Bu->getRowMap();
818 Bview.colMap = Bu->getColMap();
819 Bview.domainMap = Bu->getDomainMap();
820 Bview.importColMap = Teuchos::null;
821
822 lo_view_t Bcol2Ccol(no_init_view("Bcol2Ccol"), Bview.colMap->getLocalNumElements()), Icol2Ccol;
823 const LO colMapSize = static_cast<LO>(Bview.colMap->getLocalNumElements());
824
825 local_map_type Acolmap_local = Aview.colMap->getLocalMap();
826 local_map_type Browmap_local = Bview.origMatrix->getRowMap()->getLocalMap();
827 lo_view_t targetMapToOrigRow(no_init_view("targetMapToOrigRow"), Aview.colMap->getLocalNumElements());
828 lo_view_t targetMapToImportRow;
829
830 // Copy in work
831 {
832 Teuchos::TimeMonitor tm_copyin(*TimeMonitor::getNewTimer("MM LTG: CopyIn"));
833
834 // Because we're in serial...
835 Cnc->replaceColMap(Bu->getColMap());
836
837 // Bcol2Ccol is trivial
838 Kokkos::parallel_for(
839 "Tpetra::mult_A_B_newmatrix::Bcol2Ccol_fill",
840 Kokkos::RangePolicy<execution_space, LO>(0, colMapSize),
841 KOKKOS_LAMBDA(const LO i) {
842 Bcol2Ccol(i) = i;
843 });
844
845 // Acol2Brow
846 Kokkos::parallel_for(
847 "Tpetra::mult_A_B_newmatrix::construct_tables",
848 range_type(Aview.colMap->getMinLocalIndex(),
849 Aview.colMap->getMaxLocalIndex() + 1),
850 KOKKOS_LAMBDA(const LO i) {
851 GO aidx = Acolmap_local.getGlobalElement(i);
852 LO B_LID = Browmap_local.getLocalElement(aidx);
853 if (B_LID != LO_INVALID) {
854 targetMapToOrigRow(i) = B_LID;
855 // targetMapToImportRow(i) = LO_INVALID;
856 } else {
857 // This shouldn't happen here
858 }
859 });
860
861 } // copyin
862 Au->getComm()->barrier();
863
864 // **********************************
865 // Multiply
866 Teuchos::RCP<Teuchos::ParameterList> params = Teuchos::parameterList();
867 params->set("sort entries", false);
868 {
869 Teuchos::TimeMonitor tm(*TimeMonitor::getNewTimer("MM LTG: Multiply"));
870 #ifdef USE_DESCRIPTIVE_STATS
871 ltg_mult_start = std::chrono::steady_clock::now();
872 #endif
873 #ifdef HAVE_VTUNE
874 __itt_resume();
875 #endif
876 Tpetra::MatrixMatrix::ExtraKernels::mult_A_B_newmatrix_LowThreadGustavsonKernel(
877 Aview, Bview,
878 targetMapToOrigRow, targetMapToImportRow,
879 Bcol2Ccol, Icol2Ccol,
880 *Cnc, Cimport,
881 std::string("LTG"), params);
882 #ifdef HAVE_VTUNE
883 __itt_pause();
884 #endif
885 #ifdef USE_DESCRIPTIVE_STATS
886 ltg_mult_stop = std::chrono::steady_clock::now();
887 {
888 std::chrono::duration<double> ds;
889 ds = ltg_mult_stop - ltg_mult_start;
890 my_experiment_timings["LTG: Call"].push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(ds).count());
891 }
892 #endif
893 }
894 Au->getComm()->barrier();
895 }
896 }
897 };
898 #endif // HAVE OPENMP
899
900 // =========================================================================
901 // Xpetra Testing
902 // =========================================================================
903 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
904 void Multiply_Xpetra(const Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> &A, const Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> &B, Teuchos::RCP<Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> > &C, Teuchos::RCP<Teuchos::ParameterList> params = Teuchos::null) {
905 #ifdef USE_DESCRIPTIVE_STATS
906 xpetra_mult_start = std::chrono::steady_clock::now();
907 #endif
908 Teuchos::FancyOStream fos(Teuchos::rcpFromRef(std::cout));
909 Xpetra::MatrixMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Multiply(A, false, B, false, C, fos, true, true, std::string(""), params);
910 #ifdef USE_DESCRIPTIVE_STATS
911 xpetra_mult_stop = std::chrono::steady_clock::now();
912 {
913 std::chrono::duration<double> ds;
914 ds = ltg_mult_stop - ltg_mult_start;
915 my_experiment_timings["Xpetra: Call"].push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(ds).count());
916 }
917 #endif
918 }
919
920 // =========================================================================
921 // Utilities
922 // =========================================================================
923
924 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
925 void dump_matrix(const std::string &prefix,
926 const std::string &kernel_name,
927 const Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> &C) {
928 std::ostringstream ss;
929 ss << prefix << "_" << kernel_name << ".mtx";
930 Xpetra::IO<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Write(ss.str(), C);
931 }
932
933 inline bool file_exists(const std::string &name) {
934 std::ifstream f(name.c_str());
935 return f.good();
936 }
937
938 static int prior_pos;
939 void simple_progress_bar(const int iter, std::ostream &out, const int iter_max) {
940 double progress = (double)iter / (double)iter_max;
941
942 int barWidth = 70;
943
944 if (iter == 0) prior_pos = 0;
945
946 int new_pos = barWidth * progress;
947
948 if (new_pos > prior_pos) {
949 out << "[";
950 for (int i = 0; i < barWidth; ++i) {
951 if (i < new_pos)
952 out << "=";
953 else if (i == new_pos)
954 out << ">";
955 else
956 out << " ";
957 }
958 out << "] " << int(progress * 100.0) << " %\r";
959 out.flush();
960 }
961 prior_pos = new_pos;
962 }
963
964 void print_desc_stats(const std::string &csvFile, const bool writeCSV, std::ostream &out) {
965 #if USE_DESCRIPTIVE_STATS == 1
966 typedef DescriptiveStats::ns ns;
967
968 std::ostringstream oss;
969 std::ostringstream oss_header;
970
971 // it is safe to reuse a 'stats' data structure. It will be cleared before resuse
972 DescriptiveStats::descriptive_stat_map_type stats;
973 const double timer_ratio = double(ns::period::num) / double(ns::period::den);
974
975 DescriptiveStats::print_descriptive_stats(oss_header, stats, timer_ratio, "header", true, true);
976 DescriptiveStats::profile_timer(oss);
977
978 // loop through and dump the stats to the stringstream
979 for (auto &dataset : my_experiment_timings) {
980 auto &measurements = dataset.second;
981 const bool compute_median_CI = true;
982 DescriptiveStats::get_descriptive_stats(measurements, measurements.size(), stats, compute_median_CI);
983 DescriptiveStats::print_descriptive_stats(oss, stats, timer_ratio, dataset.first, true);
984 }
985
986 // write to 'out'
987 out << oss_header.str() << oss.str();
988
989 // if rank == 0...
990 if (writeCSV) {
991 std::ofstream csv_fptr;
992 const bool haveExistingCSV = file_exists(csvFile);
993 csv_fptr.open(csvFile, std::ios_base::app);
994
995 out << " Writing CSV [" << csvFile << "]...";
996 if (!haveExistingCSV) {
997 out << "adding header...";
998 csv_fptr << oss_header.str();
999 }
1000 csv_fptr << oss.str();
1001 csv_fptr.close();
1002 out << "Wrote data... done" << std::endl;
1003 }
1004 #endif // if have descriptive stats
1005
1006 } // end print desc stats
1007
1008 // =========================================================================
1009 // =========================================================================
1010 // =========================================================================
1011 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
1012 int main_(Teuchos::CommandLineProcessor &clp, Xpetra::UnderlyingLib &lib, int argc, char *argv[]) {
1013 #include <MueLu_UseShortNames.hpp>
1014
1015 using std::endl;
1016 using Teuchos::RCP; // reference count pointers
1017 using Teuchos::rcp;
1018 using Teuchos::TimeMonitor;
1019
1020 #if USE_DESCRIPTIVE_STATS == 1
1021 typedef DescriptiveStats::Time Time;
1022 typedef DescriptiveStats::ns ns;
1023 typedef DescriptiveStats::double_secs double_secs;
1024 typedef DescriptiveStats::descriptive_stat_map_type descriptive_stat_map_type;
1025 #endif
1026
1027 #ifdef HAVE_VTUNE
1028 #pragma message "Pausing Vtune"
1029 __itt_pause();
1030 #endif
1031
1032 bool success = false;
1033 bool verbose = true;
1034 try {
1035 RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm();
1036 // disable this annoyance
1037 Teuchos::TimeMonitor::setStackedTimer(Teuchos::null);
1038
1039 // =========================================================================
1040 // Convenient definitions
1041 // =========================================================================
1042 // Instead of checking each time for rank, create a rank 0 stream
1043 RCP<Teuchos::FancyOStream> pOut = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
1044 Teuchos::FancyOStream &out = *pOut;
1045 out.setOutputToRootOnly(0);
1046
1047 // =========================================================================
1048 // Parameters initialization
1049 // =========================================================================
1050 clp.throwExceptions(false);
1051 Xpetra::Parameters xpetraParameters(clp); // manage parameters of Xpetra
1052
1053 bool printTimings = true;
1054 clp.setOption("timings", "notimings", &printTimings, "print timings to screen");
1055 bool descStats = true;
1056 clp.setOption("descStats", "nodescStats", &descStats, "track all timings and compute descriptive statistics (uses more memory+time)");
1057 int nrepeat = 100;
1058 clp.setOption("nrepeat", &nrepeat, "repeat the experiment N times");
1059 bool printFNorm = true;
1060 clp.setOption("fnorm", "nofnorm", &printFNorm, "Compute the Frobenius norm after each multiplication");
1061
1062 bool printTypes = true;
1063 clp.setOption("types", "noTypes", &printTypes, "Print the types being used");
1064 bool printMats = true;
1065 clp.setOption("printMats", "noPrintMats", &printMats, "Describe matrices");
1066 bool progressBar = true;
1067 clp.setOption("progressBar", "noProgressBar", &progressBar, "Show an ascii progress bar while executing.");
1068 bool writeCSV = false;
1069 clp.setOption("writeCSV", "noWriteCSV", &writeCSV, "Write a CSV file if descriptive stats is enabled. See --csvFile=NAME");
1070 std::string csvFile = "desc_stats.csv";
1071 clp.setOption("csvFile", &csvFile, "CSV file to store desc stats in.");
1072
1073 bool trackRssHWM = false;
1074 clp.setOption("trackRssHWM", "noTrackRssHWM", &trackRssHWM, "Track the RSS high water mark (assumes no HP usage)");
1075
1076 // the kernels
1077 bool is_serial = comm->getSize() == 1;
1078 bool do_viennaCL = is_serial;
1079 bool do_mkl = is_serial;
1080 bool do_kk_mem = is_serial;
1081 bool do_kk_dense = is_serial;
1082 bool do_kk_default = is_serial;
1083 bool do_ltg = is_serial;
1084 bool do_xpetra = true;
1085
1086 #ifndef HAVE_MUELU_VIENNACL
1087 do_viennaCL = false;
1088 #endif
1089
1090 #ifndef HAVE_MUELU_MKL
1091 do_mkl = false;
1092 #endif
1093 clp.setOption("viennaCL", "noviennaCL", &do_viennaCL, "Evaluate ViennaCL");
1094 clp.setOption("mkl", "nomkl", &do_mkl, "Evaluate MKL SpMM");
1095 clp.setOption("kk_mem", "nokk_mem", &do_kk_mem, "Evaluate KK Mem");
1096 clp.setOption("kk_dense", "nokk_dense", &do_kk_dense, "Evaluate KK Dense");
1097 clp.setOption("kk_default", "nokk_default", &do_kk_default, "Evaluate KK Default");
1098 clp.setOption("ltg", "noltg", &do_ltg, "Evaluate LTG");
1099 clp.setOption("xpetra", "noxpetra", &do_ltg, "Evaluate Xpetra");
1100
1101 std::string dump_result = "";
1102 clp.setOption("dump_result", &dump_result, "Dump the resulting matrices (once)");
1103
1104 int kk_team_work_size = 16;
1105
1106 std::string matrixFileNameA = "A.mm";
1107 clp.setOption("matrixfileA", &matrixFileNameA, "matrix market file containing matrix");
1108 std::string matrixFileNameB = "B.mm";
1109 clp.setOption("matrixfileB", &matrixFileNameB, "matrix market file containing matrix");
1110
1111 clp.recogniseAllOptions(false);
1112 switch (clp.parse(argc, argv)) {
1113 case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED: return EXIT_SUCCESS;
1114 case Teuchos::CommandLineProcessor::PARSE_ERROR:
1115 case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION: return EXIT_FAILURE;
1116 case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL: break;
1117 }
1118
1119 #ifndef HAVE_MUELU_VIENNACL
1120 if (do_viennaCL == true) {
1121 out << "ViennaCL was requested, but this kernel is not available. Disabling..." << endl;
1122 do_viennaCL = false;
1123 }
1124 #endif
1125
1126 #ifndef HAVE_MUELU_MKL
1127 if (do_mkl == true) {
1128 out << "MKL was requested, but this kernel is not available. Disabling..." << endl;
1129 do_mkl = false;
1130 }
1131 #endif
1132
1133 // simple hack to randomize order of experiments
1134 std::vector<Experiments> my_experiments;
1135 // add the experiments we will run
1136 #ifdef HAVE_MUELU_VIENNACL
1137 if (do_viennaCL) my_experiments.push_back(Experiments::ViennaCL); // ViennaCL
1138 #endif
1139
1140 #ifdef HAVE_MUELU_MKL
1141 if (do_mkl) my_experiments.push_back(Experiments::MKL_SPMM); // MKL SPMM
1142 #endif
1143
1144 // assume these are available
1145 if (do_kk_mem) my_experiments.push_back(Experiments::KK_MEM); // KK Mem
1146 if (do_kk_dense) my_experiments.push_back(Experiments::KK_DENSE); // KK Dense
1147 if (do_kk_default) my_experiments.push_back(Experiments::KK_DEFAULT); // KK Default
1148 if (do_ltg) my_experiments.push_back(Experiments::LTG); // LTG
1149 if (do_xpetra) my_experiments.push_back(Experiments::XPETRA); // Xpetra
1150 if (printTypes) {
1151 out << "========================================================" << endl
1152 << xpetraParameters
1153 // << matrixParameters
1154 << "========================================================" << endl
1155 << "Template Types:" << endl
1156 << " Scalar: " << Teuchos::demangleName(typeid(SC).name()) << endl
1157 << " LocalOrdinal: " << Teuchos::demangleName(typeid(LO).name()) << endl
1158 << " GlobalOrdinal: " << Teuchos::demangleName(typeid(GO).name()) << endl
1159 << " Node: " << Teuchos::demangleName(typeid(NO).name()) << endl
1160 << "Sizes:" << endl
1161 << " Scalar: " << sizeof(SC) << endl
1162 << " LocalOrdinal: " << sizeof(LO) << endl
1163 << " GlobalOrdinal: " << sizeof(GO) << endl
1164 << "========================================================" << endl
1165 << "Matrix: " << Teuchos::demangleName(typeid(Matrix).name()) << endl
1166 << "Vector: " << Teuchos::demangleName(typeid(Vector).name()) << endl
1167 << "Hierarchy: " << Teuchos::demangleName(typeid(Hierarchy).name()) << endl
1168 << "========================================================" << endl;
1169 }
1170
1171 // bool dump_matrices = false;
1172 // if (dump_result != "") dump_matrices = true;
1173
1174 // Teuchos::TimeMonitor::setStackedTimer(Teuchos::null);
1175
1176 std::stringstream ss;
1177
1178 // this stuff was designed to report nested parallelism it isn't super helpful
1179 // but at some point I was working with OMP_NESTED=true, which is very different
1180 // from Kokkos' team based parallelism with OpenMP
1181 #ifdef HAVE_MUELU_OPENMP
1182 #pragma omp parallel
1183 {
1184 int num_threads = omp_get_num_threads();
1185
1186 #pragma omp for ordered
1187 for (int n = 0; n < num_threads; n++) {
1188 #pragma omp critical
1189 {
1190 ss << "Level: " << omp_get_level()
1191 << ", Active Level: " << omp_get_active_level()
1192 << ", Team #: " << omp_get_team_num() + 1 << " / " << omp_get_num_teams()
1193 << ", Thread: " << omp_get_thread_num() + 1 << " / " << omp_get_num_threads()
1194 << ", cpu: " << sched_getcpu()
1195 << std::endl;
1196 }
1197
1198 #pragma omp parallel
1199 {
1200 if (omp_get_active_level() == omp_get_level()) {
1201 #pragma omp critical
1202 {
1203 ss << "Level: " << omp_get_level()
1204 << ", Active Level: " << omp_get_active_level()
1205 << ", Parent TID: " << omp_get_ancestor_thread_num(1) + 1
1206 << ", Team #: " << omp_get_team_num() + 1 << " / " << omp_get_num_teams()
1207 << ", Team Size: " << omp_get_team_size(2)
1208 << ", Thread: " << omp_get_thread_num() + 1 << " / " << omp_get_num_threads()
1209 << ", cpu: " << sched_getcpu()
1210 << std::endl;
1211 }
1212 } else {
1213 #pragma omp critical
1214 {
1215 ss << "Level: " << omp_get_level()
1216 << ", Active Level: " << omp_get_active_level()
1217 << ", Parent TID: " << omp_get_ancestor_thread_num(1) + 1
1218 << ", Team #: " << omp_get_team_num() + 1 << " / " << omp_get_num_teams()
1219 << ", Team Size: " << omp_get_team_size(2)
1220 << ", Thread: " << omp_get_thread_num() + 1 << " / " << omp_get_num_threads()
1221 << ", cpu: " << sched_getcpu()
1222 << std::endl;
1223 }
1224 }
1225 }
1226 }
1227 }
1228
1229 out << ss.str();
1230 out.flush();
1231 #endif // have openmp
1232
1233 // =========================================================================
1234 // Problem construction
1235 // =========================================================================
1236 RCP<TimeMonitor> globalTimeMonitor = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("MatrixRead: S - Global Time")));
1237
1238 comm->barrier();
1239
1240 RCP<Matrix> A = Xpetra::IO<SC, LO, GO, Node>::Read(std::string(matrixFileNameA), lib, comm);
1241 RCP<Matrix> B;
1242
1243 if (matrixFileNameB == "dupe") {
1244 B = A;
1245
1246 if (verbose) out << "duplicating A" << endl;
1247 } else if (matrixFileNameB == "alias") {
1248 B = A;
1249 if (verbose) out << "Aliasing A" << endl;
1250 } else {
1251 B = Xpetra::IO<SC, LO, GO, Node>::Read(std::string(matrixFileNameB), lib, comm);
1252 }
1253
1254 globalTimeMonitor = Teuchos::null;
1255 comm->barrier();
1256
1257 if (verbose) {
1258 out << "Matrix Read complete." << endl;
1259 }
1260
1261 if (printMats) {
1262 out << "Matrix A:" << endl
1263 << *A
1264 << "========================================================" << endl
1265 << "Matrix B:" << endl
1266 << *B
1267 << "========================================================" << endl;
1268 // if (do_serial)
1269 // out << "Matrix A:" << endl
1270 // << *Aserial
1271 // << "========================================================" << endl
1272 // << "Matrix B:" << endl
1273 // << *Bserial
1274 // << "========================================================" << endl;
1275 }
1276
1277 // random source
1278 std::random_device rd;
1279 std::mt19937 random_source(rd());
1280
1281 // no need for a barrier, because the randomization process uses a collective.
1282 if (!my_experiments.empty()) {
1283 std::vector<double> mem_dummy;
1284 double prior_fnorm = std::numeric_limits<double>::max();
1285 int fnorm_failures = 0;
1286
1287 globalTimeMonitor = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Kernels Total Time")));
1288 for (int i = 0; i < nrepeat; i++) {
1289 // randomize the experiments
1290 if (comm->getRank() == 0) {
1291 std::shuffle(my_experiments.begin(), my_experiments.end(), random_source);
1292 }
1293 // Broadcast this ordering to the other processes
1294 comm->broadcast(0,
1295 static_cast<int>(sizeof(Experiments::LTG) * my_experiments.size()),
1296 reinterpret_cast<char *>(my_experiments.data()));
1297
1298 // loop over the randomized experiments
1299 for (const auto &experiment_id : my_experiments) {
1300 RCP<Matrix> C;
1301 std::string kernel_name = to_string(experiment_id);
1302 #if USE_DESCRIPTIVE_STATS == 1
1303 auto &timing_vector = my_experiment_timings[kernel_name + ": Total"];
1304 auto &mem_vector = (trackRssHWM) ? my_experiment_timings[kernel_name + ": RssHWM"] : mem_dummy;
1305 #endif
1306
1307 switch (experiment_id) {
1308 // ViennaCL
1309 case Experiments::ViennaCL:
1310 #ifdef HAVE_MUELU_VIENNACL
1311 C = Xpetra::MatrixFactory<SC, LO, GO, Node>::Build(A->getRowMap(), 0);
1312 {
1313 TimeMonitor t(*TimeMonitor::getNewTimer("MM ViennaCL: Total"));
1314 DescriptiveTime(Multiply_ViennaCL(*A, *B, *C));
1315 }
1316 #endif
1317 break;
1318 // MKL_SPMM
1319 case Experiments::MKL_SPMM:
1320 #ifdef HAVE_MUELU_MKL
1321 C = Xpetra::MatrixFactory<SC, LO, GO, Node>::Build(A->getRowMap(), 0);
1322 {
1323 TimeMonitor t(*TimeMonitor::getNewTimer("MM MKL: Total"));
1324 DescriptiveTime(Multiply_MKL_SPMM(*A, *B, *C));
1325 }
1326 #endif
1327 break;
1328 // KK Algorithms (KK Memory)
1329 case Experiments::KK_MEM:
1330 C = Xpetra::MatrixFactory<SC, LO, GO, Node>::Build(A->getRowMap(), 0);
1331 {
1332 TimeMonitor t(*TimeMonitor::getNewTimer("MM SPGEMM_KK_MEMORY: Total"));
1333 DescriptiveTime(Multiply_KokkosKernels(*A, *B, *C, std::string("SPGEMM_KK_MEMORY"), kk_team_work_size));
1334 }
1335 break;
1336 // KK Algorithms (KK Dense)
1337 case Experiments::KK_DENSE:
1338 C = Xpetra::MatrixFactory<SC, LO, GO, Node>::Build(A->getRowMap(), 0);
1339 {
1340 TimeMonitor t(*TimeMonitor::getNewTimer("MM SPGEMM_KK_DENSE: Total"));
1341 DescriptiveTime(Multiply_KokkosKernels(*A, *B, *C, std::string("SPGEMM_KK_DENSE"), kk_team_work_size));
1342 }
1343 break;
1344 // KK Algorithms (KK Default)
1345 case Experiments::KK_DEFAULT:
1346 C = Xpetra::MatrixFactory<SC, LO, GO, Node>::Build(A->getRowMap(), 0);
1347 {
1348 TimeMonitor t(*TimeMonitor::getNewTimer("MM SPGEMM_KK: Total"));
1349 DescriptiveTime(Multiply_KokkosKernels(*A, *B, *C, std::string("SPGEMM_KK"), kk_team_work_size));
1350 }
1351 break;
1352 // LTG
1353 case Experiments::LTG:
1354 C = Xpetra::MatrixFactory<SC, LO, GO, Node>::Build(A->getRowMap(), 0);
1355 {
1356 TimeMonitor t(*TimeMonitor::getNewTimer("MM LTG: Total"));
1357 using ltg_tester = LTG_Tests<SC, LO, GO, Node>;
1358 DescriptiveTime(ltg_tester::Multiply_LTG(*A, *B, *C));
1359 }
1360 break;
1361 // Xpetra
1362 case Experiments::XPETRA:
1363 C = Xpetra::MatrixFactory<SC, LO, GO, Node>::Build(A->getRowMap(), 0);
1364 {
1365 TimeMonitor t(*TimeMonitor::getNewTimer("MM XPETRA: Total"));
1366 DescriptiveTime(Multiply_Xpetra(*A, *B, C));
1367 }
1368 break;
1369
1370 default:
1371 std::cerr << "Unknown experiment ID encountered: " << (int)experiment_id << std::endl;
1372 }
1373 comm->barrier();
1374
1375 if (printFNorm) {
1376 const auto current_fnorm = C->getFrobeniusNorm();
1377 const bool fnorm_error = (std::abs(current_fnorm - prior_fnorm) / prior_fnorm) > 1.e-14;
1378 if (i == 0) {
1379 out << kernel_name << " "
1380 << "Current Fnorm: " << current_fnorm
1381 << std::endl;
1382 } else if (fnorm_error) {
1383 out << kernel_name << " "
1384 << "Current Fnorm: " << current_fnorm << ", Difference from Prior: "
1385 << std::abs(prior_fnorm - current_fnorm)
1386 << std::endl;
1387 fnorm_failures++;
1388 }
1389 prior_fnorm = current_fnorm;
1390 }
1391 C = Teuchos::null;
1392 } // end random exp loop
1393
1394 if (progressBar) simple_progress_bar(i, out, nrepeat);
1395 } // end repeat
1396 } // end ! my_experiments.empty()
1397
1398 globalTimeMonitor = Teuchos::null;
1399
1400 if (printTimings) {
1401 TimeMonitor::summarize(comm.ptr(), std::cout, false, true, false, Teuchos::Union, "", true);
1402 #if USE_DESCRIPTIVE_STATS == 1
1403
1404 if (descStats) print_desc_stats(csvFile, writeCSV, out);
1405 #endif
1406 }
1407
1408 success = true;
1409 }
1410 TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success);
1411
1412 return (success ? EXIT_SUCCESS : EXIT_FAILURE);
1413 } // main
1414
1415 //- -- --------------------------------------------------------
1416 #define MUELU_AUTOMATIC_TEST_ETI_NAME main_
1417 #include "MueLu_Test_ETI.hpp"
1418
1419 int main(int argc, char *argv[]) {
1420 return Automatic_Test_ETI(argc, argv);
1421 }