Reference documentation for deal.II version 8.4.1
mpi.cc
1 // ---------------------------------------------------------------------
2 //
3 // Copyright (C) 2005 - 2015 by the deal.II authors
4 //
5 // This file is part of the deal.II library.
6 //
7 // The deal.II library is free software; you can use it, redistribute
8 // it, and/or modify it under the terms of the GNU Lesser General
9 // Public License as published by the Free Software Foundation; either
10 // version 2.1 of the License, or (at your option) any later version.
11 // The full text of the license can be found in the file LICENSE at
12 // the top level of the deal.II distribution.
13 //
14 // ---------------------------------------------------------------------
15 
16 
17 #include <deal.II/base/mpi.h>
18 #include <deal.II/base/utilities.h>
19 #include <deal.II/base/exceptions.h>
20 #include <deal.II/lac/vector_memory.h>
21 #include <deal.II/lac/parallel_vector.h>
22 #include <deal.II/lac/parallel_block_vector.h>
23 #include <deal.II/base/multithread_info.h>
24 
25 #include <cstddef>
26 #include <iostream>
27 
28 #ifdef DEAL_II_WITH_TRILINOS
29 # ifdef DEAL_II_WITH_MPI
30 # include <Epetra_MpiComm.h>
31 # include <deal.II/lac/vector_memory.h>
32 # include <deal.II/lac/trilinos_vector.h>
33 # include <deal.II/lac/trilinos_block_vector.h>
34 # endif
35 #endif
36 
37 #ifdef DEAL_II_WITH_PETSC
38 # ifdef DEAL_II_WITH_MPI
39 # include <petscsys.h>
40 # include <deal.II/lac/petsc_block_vector.h>
41 # include <deal.II/lac/petsc_parallel_block_vector.h>
42 # include <deal.II/lac/petsc_vector.h>
43 # include <deal.II/lac/petsc_parallel_vector.h>
44 # endif
45 #endif
46 
47 #ifdef DEAL_II_WITH_SLEPC
48 # ifdef DEAL_II_WITH_MPI
49 # include <slepcsys.h>
50 # endif
51 #endif
52 
53 DEAL_II_NAMESPACE_OPEN
54 
55 
56 namespace Utilities
57 {
58 
59  namespace MPI
60  {
61 #ifdef DEAL_II_WITH_MPI
62  // Unfortunately, we have to work
63  // around an oddity in the way PETSc
64  // and some gcc versions interact. If
65  // we use PETSc's MPI dummy
66  // implementation, it expands the
67  // calls to the two MPI functions
68  // basically as ``(n_jobs=1, 0)'',
69  // i.e. it assigns the number one to
70  // the variable holding the number of
71  // jobs, and then uses the comma
72  // operator to let the entire
73  // expression have the value zero. The
74  // latter is important, since
75  // ``MPI_Comm_size'' returns an error
76  // code that we may want to check (we
77  // don't here, but one could in
78  // principle), and the trick with the
79  // comma operator makes sure that both
80  // the number of jobs is correctly
81  // assigned, and the return value is
82  // zero. Unfortunately, if some recent
83  // versions of gcc detect that the
84  // comma expression just stands by
85  // itself, i.e. the result is not
86  // assigned to another variable, then
87  // they warn ``right-hand operand of
88  // comma has no effect''. This
89  // unwanted side effect can be
90  // suppressed by casting the result of
91  // the entire expression to type
92  // ``void'' -- not beautiful, but
93  // helps calming down unwarranted
94  // compiler warnings...
95  unsigned int n_mpi_processes (const MPI_Comm &mpi_communicator)
96  {
97  int n_jobs=1;
98  (void) MPI_Comm_size (mpi_communicator, &n_jobs);
99 
100  return n_jobs;
101  }
102 
103 
104  unsigned int this_mpi_process (const MPI_Comm &mpi_communicator)
105  {
106  int rank=0;
107  (void) MPI_Comm_rank (mpi_communicator, &rank);
108 
109  return rank;
110  }
111 
112 
113  MPI_Comm duplicate_communicator (const MPI_Comm &mpi_communicator)
114  {
115  MPI_Comm new_communicator;
116  MPI_Comm_dup (mpi_communicator, &new_communicator);
117  return new_communicator;
118  }
119 
120 
121  std::vector<unsigned int>
123  const std::vector<unsigned int> &destinations)
124  {
125  unsigned int myid = Utilities::MPI::this_mpi_process(mpi_comm);
126  unsigned int n_procs = Utilities::MPI::n_mpi_processes(mpi_comm);
127 
128  for (unsigned int i=0; i<destinations.size(); ++i)
129  {
130  Assert (destinations[i] < n_procs,
131  ExcIndexRange (destinations[i], 0, n_procs));
132  Assert (destinations[i] != myid,
133  ExcMessage ("There is no point in communicating with ourselves."));
134  }
135 
136 
137  // let all processors
138  // communicate the maximal
139  // number of destinations they
140  // have
141  const unsigned int max_n_destinations
142  = Utilities::MPI::max (destinations.size(), mpi_comm);
143 
144  if (max_n_destinations==0)
145  // all processes have nothing to send/receive:
146  return std::vector<unsigned int>();
147 
148  // now that we know the number
149  // of data packets every
150  // processor wants to send, set
151  // up a buffer with the maximal
152  // size and copy our
153  // destinations in there,
154  // padded with -1's
155  std::vector<unsigned int> my_destinations(max_n_destinations,
157  std::copy (destinations.begin(), destinations.end(),
158  my_destinations.begin());
159 
160  // now exchange these (we could
161  // communicate less data if we
162  // used MPI_Allgatherv, but
163  // we'd have to communicate
164  // my_n_destinations to all
165  // processors in this case,
166  // which is more expensive than
167  // the reduction operation
168  // above in MPI_Allreduce)
169  std::vector<unsigned int> all_destinations (max_n_destinations * n_procs);
170  MPI_Allgather (&my_destinations[0], max_n_destinations, MPI_UNSIGNED,
171  &all_destinations[0], max_n_destinations, MPI_UNSIGNED,
172  mpi_comm);
173 
174  // now we know who is going to
175  // communicate with
176  // whom. collect who is going
177  // to communicate with us!
178  std::vector<unsigned int> origins;
179  for (unsigned int i=0; i<n_procs; ++i)
180  for (unsigned int j=0; j<max_n_destinations; ++j)
181  if (all_destinations[i*max_n_destinations + j] == myid)
182  origins.push_back (i);
183  else if (all_destinations[i*max_n_destinations + j] ==
185  break;
186 
187  return origins;
188  }
189 
190 
191  namespace
192  {
193  // custom MIP_Op for calculate_collective_mpi_min_max_avg
194  void max_reduce ( const void *in_lhs_,
195  void *inout_rhs_,
196  int *len,
197  MPI_Datatype *)
198  {
199  (void)len;
200  const MinMaxAvg *in_lhs = static_cast<const MinMaxAvg *>(in_lhs_);
201  MinMaxAvg *inout_rhs = static_cast<MinMaxAvg *>(inout_rhs_);
202 
203  Assert(*len==1, ExcInternalError());
204 
205  inout_rhs->sum += in_lhs->sum;
206  if (inout_rhs->min>in_lhs->min)
207  {
208  inout_rhs->min = in_lhs->min;
209  inout_rhs->min_index = in_lhs->min_index;
210  }
211  else if (inout_rhs->min == in_lhs->min)
212  {
213  // choose lower cpu index when tied to make operator commutative
214  if (inout_rhs->min_index > in_lhs->min_index)
215  inout_rhs->min_index = in_lhs->min_index;
216  }
217 
218  if (inout_rhs->max < in_lhs->max)
219  {
220  inout_rhs->max = in_lhs->max;
221  inout_rhs->max_index = in_lhs->max_index;
222  }
223  else if (inout_rhs->max == in_lhs->max)
224  {
225  // choose lower cpu index when tied to make operator commutative
226  if (inout_rhs->max_index > in_lhs->max_index)
227  inout_rhs->max_index = in_lhs->max_index;
228  }
229  }
230  }
231 
232 
233 
234  MinMaxAvg
235  min_max_avg(const double my_value,
236  const MPI_Comm &mpi_communicator)
237  {
238  // If MPI was not started, we have a serial computation and cannot run
239  // the other MPI commands
240  if (job_supports_mpi() == false)
241  {
242  MinMaxAvg result;
243  result.sum = my_value;
244  result.avg = my_value;
245  result.min = my_value;
246  result.max = my_value;
247  result.min_index = 0;
248  result.max_index = 0;
249 
250  return result;
251  }
252 
253  // To avoid uninitialized values on some MPI implementations, provide
254  // result with a default value already...
255  MinMaxAvg result = { 0., std::numeric_limits<double>::max(),
256  -std::numeric_limits<double>::max(), 0, 0, 0.
257  };
258 
259  const unsigned int my_id
260  = ::Utilities::MPI::this_mpi_process(mpi_communicator);
261  const unsigned int numproc
262  = ::Utilities::MPI::n_mpi_processes(mpi_communicator);
263 
264  MPI_Op op;
265  int ierr = MPI_Op_create((MPI_User_function *)&max_reduce, true, &op);
266  AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());
267 
268  MinMaxAvg in;
269  in.sum = in.min = in.max = my_value;
270  in.min_index = in.max_index = my_id;
271 
272  MPI_Datatype type;
273  int lengths[]= {3,2};
274  MPI_Aint displacements[]= {0,offsetof(MinMaxAvg, min_index)};
275  MPI_Datatype types[]= {MPI_DOUBLE, MPI_INT};
276 
277  ierr = MPI_Type_struct(2, lengths, displacements, types, &type);
278  AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());
279 
280  ierr = MPI_Type_commit(&type);
281  ierr = MPI_Allreduce (&in, &result, 1, type, op, mpi_communicator);
282  AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());
283 
284  ierr = MPI_Type_free (&type);
285  AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());
286 
287  ierr = MPI_Op_free(&op);
288  AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());
289 
290  result.avg = result.sum / numproc;
291 
292  return result;
293  }
294 
295 #else
296 
297  unsigned int n_mpi_processes (const MPI_Comm &)
298  {
299  return 1;
300  }
301 
302 
303 
304  unsigned int this_mpi_process (const MPI_Comm &)
305  {
306  return 0;
307  }
308 
309 
310  MPI_Comm duplicate_communicator (const MPI_Comm &mpi_communicator)
311  {
312  return mpi_communicator;
313  }
314 
315 
316 
317  MinMaxAvg
318  min_max_avg(const double my_value,
319  const MPI_Comm &)
320  {
321  MinMaxAvg result;
322 
323  result.sum = my_value;
324  result.avg = my_value;
325  result.min = my_value;
326  result.max = my_value;
327  result.min_index = 0;
328  result.max_index = 0;
329 
330  return result;
331  }
332 
333 #endif
334 
335 
336 
338  char ** &argv,
339  const unsigned int max_num_threads)
340  {
341  static bool constructor_has_already_run = false;
342  (void)constructor_has_already_run;
343  Assert (constructor_has_already_run == false,
344  ExcMessage ("You can only create a single object of this class "
345  "in a program since it initializes the MPI system."));
346 
347 
348 
349 #ifdef DEAL_II_WITH_MPI
350  // if we have PETSc, we will initialize it and let it handle MPI.
351  // Otherwise, we will do it.
352  int MPI_has_been_started = 0;
353  MPI_Initialized(&MPI_has_been_started);
354  AssertThrow (MPI_has_been_started == 0,
355  ExcMessage ("MPI error. You can only start MPI once!"));
356 
357  int mpi_err, provided;
358  // this works like mpi_err = MPI_Init (&argc, &argv); but tells MPI that
359  // we might use several threads but never call two MPI functions at the
360  // same time. For an explanation see on why we do this see
361  // http://www.open-mpi.org/community/lists/users/2010/03/12244.php
362  int wanted = MPI_THREAD_SERIALIZED;
363  mpi_err = MPI_Init_thread(&argc, &argv, wanted, &provided);
364  AssertThrow (mpi_err == 0,
365  ExcMessage ("MPI could not be initialized."));
366 
367  // disable for now because at least some implementations always return MPI_THREAD_SINGLE.
368  //Assert(max_num_threads==1 || provided != MPI_THREAD_SINGLE,
369  // ExcMessage("MPI reports that we are not allowed to use multiple threads."));
370 #else
371  // make sure the compiler doesn't warn
372  // about these variables
373  (void)argc;
374  (void)argv;
375 #endif
376 
377  // we are allowed to call MPI_Init ourselves and PETScInitialize will
378  // detect this. This allows us to use MPI_Init_thread instead.
379 #ifdef DEAL_II_WITH_PETSC
380 # ifdef DEAL_II_WITH_SLEPC
381  // Initialize SLEPc (with PETSc):
382  SlepcInitialize(&argc, &argv, PETSC_NULL, PETSC_NULL);
383 # else
384  // or just initialize PETSc alone:
385  PetscInitialize(&argc, &argv, PETSC_NULL, PETSC_NULL);
386 # endif
387 #endif
388 
389  constructor_has_already_run = true;
390 
391 
392  // Now also see how many threads we'd like to run
393  if (max_num_threads != numbers::invalid_unsigned_int)
394  {
395  // set maximum number of threads (also respecting the environment
396  // variable that the called function evaluates) based on what
397  // the user asked
398  MultithreadInfo::set_thread_limit(max_num_threads);
399  }
400  else
401  // user wants automatic choice
402  {
403 #ifdef DEAL_II_WITH_MPI
404  // we need to figure out how many MPI processes there
405  // are on the current node, as well as how many CPU cores
406  // we have. for the first task, check what get_hostname()
407  // returns and then to an allgather so each processor
408  // gets the answer
409  //
410  // in calculating the length of the string, don't forget the
411  // terminating \0 on C-style strings
412  const std::string hostname = Utilities::System::get_hostname();
413  const unsigned int max_hostname_size = Utilities::MPI::max (hostname.size()+1,
414  MPI_COMM_WORLD);
415  std::vector<char> hostname_array (max_hostname_size);
416  std::copy (hostname.c_str(), hostname.c_str()+hostname.size()+1,
417  hostname_array.begin());
418 
419  std::vector<char> all_hostnames(max_hostname_size *
420  MPI::n_mpi_processes(MPI_COMM_WORLD));
421  MPI_Allgather (&hostname_array[0], max_hostname_size, MPI_CHAR,
422  &all_hostnames[0], max_hostname_size, MPI_CHAR,
423  MPI_COMM_WORLD);
424 
425  // search how often our own hostname appears and the
426  // how-manyth instance the current process represents
427  unsigned int n_local_processes=0;
428  unsigned int nth_process_on_host = 0;
429  for (unsigned int i=0; i<MPI::n_mpi_processes(MPI_COMM_WORLD); ++i)
430  if (std::string (&all_hostnames[0] + i*max_hostname_size) == hostname)
431  {
432  ++n_local_processes;
433  if (i <= MPI::this_mpi_process (MPI_COMM_WORLD))
434  ++nth_process_on_host;
435  }
436  Assert (nth_process_on_host > 0, ExcInternalError());
437 
438 
439  // compute how many cores each process gets. if the number does
440  // not divide evenly, then we get one more core if we are
441  // among the first few processes
442  //
443  // if the number would be zero, round up to one since every
444  // process needs to have at least one thread
445  const unsigned int n_threads
446  = std::max(MultithreadInfo::n_cores() / n_local_processes
447  +
448  (nth_process_on_host <= MultithreadInfo::n_cores() % n_local_processes
449  ?
450  1
451  :
452  0),
453  1U);
454 #else
455  const unsigned int n_threads = MultithreadInfo::n_cores();
456 #endif
457 
458  // finally set this number of threads
460  }
461  }
462 
463 
465  {
466  // make memory pool release all PETSc/Trilinos/MPI-based vectors that are no
467  // longer used at this point. this is relevant because the
468  // static object destructors run for these vectors at the end of
469  // the program would run after MPI_Finalize is called, leading
470  // to errors
471 
472 #ifdef DEAL_II_WITH_MPI
473  // Start with the deal.II MPI vectors (need to do this before finalizing
474  // PETSc because it finalizes MPI). Delete vectors from the pools:
476  ::release_unused_memory ();
478  ::release_unused_memory ();
480  ::release_unused_memory ();
482  ::release_unused_memory ();
483 
484  // Next with Trilinos:
485 # if defined(DEAL_II_WITH_TRILINOS)
490 # endif
491 #endif
492 
493 
494  // Now deal with PETSc (with or without MPI). Only delete the vectors if finalize hasn't
495  // been called yet, otherwise this will lead to errors.
496 #ifdef DEAL_II_WITH_PETSC
497  if ((PetscInitializeCalled == PETSC_TRUE)
498  &&
499  (PetscFinalizeCalled == PETSC_FALSE))
500  {
509 
510 # ifdef DEAL_II_WITH_SLEPC
511  // and now end SLEPc (with PETSc)
512  SlepcFinalize();
513 # else
514  // or just end PETSc.
515  PetscFinalize();
516 # endif
517  }
518 #endif
519 
520 
521  // only MPI_Finalize if we are running with MPI. We also need to do this
522  // when running PETSc, because we initialize MPI ourselves before calling
523  // PetscInitialize
524 #ifdef DEAL_II_WITH_MPI
525  if (job_supports_mpi() == true)
526  {
527  if (std::uncaught_exception())
528  {
529  std::cerr << "ERROR: Uncaught exception in MPI_InitFinalize on proc "
530  << this_mpi_process(MPI_COMM_WORLD)
531  << ". Skipping MPI_Finalize() to avoid a deadlock."
532  << std::endl;
533  }
534  else
535  {
536  const int mpi_err = MPI_Finalize();
537  AssertThrow (mpi_err == 0,
538  ExcMessage ("An error occurred while calling MPI_Finalize()"));
539  }
540  }
541 #endif
542  }
543 
544 
545  } // end of namespace MPI
546 
547 } // end of namespace Utilities
548 
549 DEAL_II_NAMESPACE_CLOSE
static const unsigned int invalid_unsigned_int
Definition: types.h:164
static void release_unused_memory()
::ExceptionBase & ExcMessage(std::string arg1)
static unsigned int n_cores()
MPI_InitFinalize(int &argc, char **&argv, const unsigned int max_num_threads=numbers::invalid_unsigned_int)
Definition: mpi.cc:337
#define AssertThrow(cond, exc)
Definition: exceptions.h:358
Definition: types.h:30
#define Assert(cond, exc)
Definition: exceptions.h:294
unsigned int n_mpi_processes(const MPI_Comm &mpi_communicator)
Definition: mpi.cc:95
Definition: mpi.h:55
std::string get_hostname()
Definition: utilities.cc:643
MPI_Comm duplicate_communicator(const MPI_Comm &mpi_communicator)
Definition: mpi.cc:113
static void set_thread_limit(const unsigned int max_threads=numbers::invalid_unsigned_int)
unsigned int this_mpi_process(const MPI_Comm &mpi_communicator)
Definition: mpi.cc:104
MinMaxAvg min_max_avg(const double my_value, const MPI_Comm &mpi_communicator)
Definition: mpi.cc:235
std::vector< unsigned int > compute_point_to_point_communication_pattern(const MPI_Comm &mpi_comm, const std::vector< unsigned int > &destinations)
Definition: mpi.cc:122
bool job_supports_mpi()
Definition: mpi.h:746
T max(const T &t, const MPI_Comm &mpi_communicator)
Definition: mpi.h:689