dimanche 15 mars 2020

How to ensure std::mt19937 generates reproducible random numbers with boost::mpi

I have a large parallel application in which I need to generate reproducible pseudo-random numbers. Can anyone explain why the minimal example below does not generate the same numbers every time?

Omitting the line "cout << "PROC" << endl;" seems to fix the problem, but why?

//compile: mpic++ -Wall mpi_rng_test.cpp -o mpi_rng_test -lboost_mpi -lboost_serialization
//run: mpirun -np 4 ./mpi_rng_test

#include <boost/mpi.hpp>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <random>

#define LOOPS 1000

namespace mpi = boost::mpi;
using namespace std;
mt19937 rng;

int main(int argc, char* argv[])
{
   mpi::environment env(argc, argv);
   mpi::communicator world;

   if (world.rank() == 0) {
      rng.seed(1);
      for (int m = 0; m <= LOOPS; m++){
         string my_string = "MAIN";
         for (int proc = 1; proc < world.size(); ++proc){
            string outmessage = to_string(m);
            world.send(proc, 0, outmessage);
         }
         vector<string> all_strings;
         gather(world, my_string, all_strings, 0);

         uniform_real_distribution<double> disR0(0.0, 1.0);
         uniform_int_distribution<int> disI1(0, 10000);
         for (int i = 0; i < LOOPS; i++)
            if (disR0(rng) < 0.5)
               cout << disI1(rng) << endl;
      }
   }
   else {
      string inmessage;
      while(inmessage.compare(to_string(LOOPS)) != 0){
         world.recv(0,0,inmessage);
         cout << "PROC" << endl;
         gather(world, to_string(world.rank()), 0);
      }
   }
   return 0;
}

In Linux, I test if the number sequence is reproducible by running this in the terminal:

mpirun -np 4 ./mpi_rng_test | grep -v PROC > a
mpirun -np 4 ./mpi_rng_test | grep -v PROC > b
diff a b



Aucun commentaire:

Enregistrer un commentaire