Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
20e22c73fdf2870c2ae679b697ea3feb07d78872
[simgrid.git] / src / smpi / internals / smpi_bench.cpp
1 /* Copyright (c) 2007-2019. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include "getopt.h"
7 #include "private.hpp"
8 #include "simgrid/host.h"
9 #include "simgrid/modelchecker.h"
10 #include "simgrid/s4u/Exec.hpp"
11 #include "smpi_comm.hpp"
12 #include "src/internal_config.h"
13 #include "src/mc/mc_replay.hpp"
14 #include "xbt/config.hpp"
15
16 #include "src/smpi/include/smpi_actor.hpp"
17 #include <unordered_map>
18
19 #ifndef WIN32
20 #include <sys/mman.h>
21 #endif
22 #include <cmath>
23
24 #if HAVE_PAPI
25 #include <papi.h>
26 #endif
27
28 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_bench, smpi, "Logging specific to SMPI (benchmarking)");
29
30 static simgrid::config::Flag<double>
31     smpi_wtime_sleep("smpi/wtime",
32                      "Minimum time to inject inside a call to MPI_Wtime(), gettimeofday() and clock_gettime()",
33                      1e-8 /* Documented to be 10 ns */);
34
35 double smpi_cpu_threshold = -1;
36 double smpi_host_speed;
37
38 SharedMallocType smpi_cfg_shared_malloc = SharedMallocType::GLOBAL;
39 double smpi_total_benched_time = 0;
40
41 // Private execute_flops used by smpi_execute and spmi_execute_benched
42 void private_execute_flops(double flops) {
43   xbt_assert(flops >= 0, "You're trying to execute a negative amount of flops (%f)!", flops);
44   XBT_DEBUG("Handle real computation time: %f flops", flops);
45   simgrid::s4u::this_actor::exec_init(flops)
46       ->set_name("computation")
47       ->set_tracing_category(smpi_process()->get_tracing_category())
48       ->start()
49       ->wait();
50   smpi_switch_data_segment(simgrid::s4u::Actor::self());
51 }
52
53 void smpi_execute_flops(double flops) {
54   int rank     = simgrid::s4u::this_actor::get_pid();
55   TRACE_smpi_computing_in(rank, flops);
56
57   private_execute_flops(flops);
58
59   TRACE_smpi_computing_out(rank);
60 }
61
62 void smpi_execute(double duration)
63 {
64   if (duration >= smpi_cpu_threshold) {
65     XBT_DEBUG("Sleep for %g to handle real computation time", duration);
66     double flops = duration * smpi_host_speed;
67     int rank     = simgrid::s4u::this_actor::get_pid();
68     TRACE_smpi_computing_in(rank, flops);
69
70     private_execute_flops(flops);
71
72     TRACE_smpi_computing_out(rank);
73
74   } else {
75     XBT_DEBUG("Real computation took %g while option smpi/cpu-threshold is set to %g => ignore it", duration,
76               smpi_cpu_threshold);
77   }
78 }
79
80 void smpi_execute_benched(double duration)
81 {
82   smpi_bench_end();
83   double speed = sg_host_speed(sg_host_self());
84   smpi_execute_flops(duration*speed);
85   smpi_bench_begin();
86 }
87
88 void smpi_bench_begin()
89 {
90   if (smpi_privatize_global_variables == SmpiPrivStrategies::MMAP) {
91     smpi_switch_data_segment(simgrid::s4u::Actor::self());
92   }
93
94   if (MC_is_active() || MC_record_replay_is_active())
95     return;
96
97 #if HAVE_PAPI
98   if (not simgrid::config::get_value<std::string>("smpi/papi-events").empty()) {
99     int event_set = smpi_process()->papi_event_set();
100     // PAPI_start sets everything to 0! See man(3) PAPI_start
101     if (PAPI_LOW_LEVEL_INITED == PAPI_is_initialized() && PAPI_start(event_set) != PAPI_OK) {
102       // TODO This needs some proper handling.
103       XBT_CRITICAL("Could not start PAPI counters.\n");
104       xbt_die("Error.");
105     }
106   }
107 #endif
108   xbt_os_threadtimer_start(smpi_process()->timer());
109 }
110
111 double smpi_adjust_comp_speed(){
112   double speedup=1;
113   if (simgrid::config::get_value<std::string>("smpi/comp-adjustment-file")[0] != '\0') {
114
115     smpi_trace_call_location_t* loc                            = smpi_process()->call_location();
116     std::string key                                            = loc->get_composed_key();
117     std::unordered_map<std::string, double>::const_iterator it = location2speedup.find(key);
118     if (it != location2speedup.end()) {
119       speedup = it->second;
120     }
121   }
122   return speedup;
123 }
124
125 void smpi_bench_end()
126 {
127   if (MC_is_active() || MC_record_replay_is_active())
128     return;
129
130   xbt_os_timer_t timer = smpi_process()->timer();
131   xbt_os_threadtimer_stop(timer);
132
133 #if HAVE_PAPI
134   /**
135    * An MPI function has been called and now is the right time to update
136    * our PAPI counters for this process.
137    */
138   if (not simgrid::config::get_value<std::string>("smpi/papi-events").empty()) {
139     papi_counter_t& counter_data        = smpi_process()->papi_counters();
140     int event_set                       = smpi_process()->papi_event_set();
141     std::vector<long long> event_values = std::vector<long long>(counter_data.size());
142
143     if (PAPI_stop(event_set, &event_values[0]) != PAPI_OK) { // Error
144       XBT_CRITICAL("Could not stop PAPI counters.\n");
145       xbt_die("Error.");
146     } else {
147       for (unsigned int i = 0; i < counter_data.size(); i++) {
148         counter_data[i].second += event_values[i];
149       }
150     }
151   }
152 #endif
153
154   if (smpi_process()->sampling()) {
155     XBT_CRITICAL("Cannot do recursive benchmarks.");
156     XBT_CRITICAL("Are you trying to make a call to MPI within a SMPI_SAMPLE_ block?");
157     xbt_backtrace_display_current();
158     xbt_die("Aborting.");
159   }
160
161   // Maybe we need to artificially speed up or slow down our computation based on our statistical analysis.
162   // Simulate the benchmarked computation unless disabled via command-line argument
163   if (simgrid::config::get_value<bool>("smpi/simulate-computation")) {
164     smpi_execute(xbt_os_timer_elapsed(timer)/smpi_adjust_comp_speed());
165   }
166
167 #if HAVE_PAPI
168   if (not simgrid::config::get_value<std::string>("smpi/papi-events").empty() && TRACE_smpi_is_enabled()) {
169     container_t container =
170         simgrid::instr::Container::by_name(std::string("rank-") + std::to_string(simgrid::s4u::this_actor::get_pid()));
171     papi_counter_t& counter_data = smpi_process()->papi_counters();
172
173     for (auto const& pair : counter_data) {
174       simgrid::instr::VariableType* variable = static_cast<simgrid::instr::VariableType*>(container->type_->by_name(pair.first));
175       variable->set_event(SIMIX_get_clock(), pair.second);
176     }
177   }
178 #endif
179
180   smpi_total_benched_time += xbt_os_timer_elapsed(timer);
181 }
182
183 /* Private sleep function used by smpi_sleep(), smpi_usleep() and friends */
184 static unsigned int private_sleep(double secs)
185 {
186   smpi_bench_end();
187
188   XBT_DEBUG("Sleep for: %lf secs", secs);
189   int rank = simgrid::s4u::this_actor::get_pid();
190   TRACE_smpi_sleeping_in(rank, secs);
191
192   simgrid::s4u::this_actor::sleep_for(secs);
193
194   TRACE_smpi_sleeping_out(rank);
195
196   smpi_bench_begin();
197   return 0;
198 }
199
200 unsigned int smpi_sleep(unsigned int secs)
201 {
202   if (not smpi_process())
203     return sleep(secs);
204   return private_sleep(secs);
205 }
206
207 int smpi_usleep(useconds_t usecs)
208 {
209   if (not smpi_process())
210     return usleep(usecs);
211   return static_cast<int>(private_sleep(usecs / 1000000.0));
212 }
213
214 #if _POSIX_TIMERS > 0
215 int smpi_nanosleep(const struct timespec* tp, struct timespec* t)
216 {
217   if (not smpi_process())
218     return nanosleep(tp,t);
219   return static_cast<int>(private_sleep(tp->tv_sec + tp->tv_nsec / 1000000000.0));
220 }
221 #endif
222
223 int smpi_gettimeofday(struct timeval* tv, struct timezone* tz)
224 {
225   if (not smpi_process())
226     return gettimeofday(tv, tz);
227
228   smpi_bench_end();
229   double now = SIMIX_get_clock();
230   if (tv) {
231     tv->tv_sec = static_cast<time_t>(now);
232 #ifdef WIN32
233     tv->tv_usec = static_cast<useconds_t>((now - tv->tv_sec) * 1e6);
234 #else
235     tv->tv_usec = static_cast<suseconds_t>((now - tv->tv_sec) * 1e6);
236 #endif
237   }
238   if (smpi_wtime_sleep > 0)
239     simgrid::s4u::this_actor::sleep_for(smpi_wtime_sleep);
240   smpi_bench_begin();
241   return 0;
242 }
243
244 #if _POSIX_TIMERS > 0
245 int smpi_clock_gettime(clockid_t clk_id, struct timespec* tp)
246 {
247   if (not smpi_process())
248     return clock_gettime(clk_id, tp);
249   //there is only one time in SMPI, so clk_id is ignored.
250   smpi_bench_end();
251   double now = SIMIX_get_clock();
252   if (tp) {
253     tp->tv_sec = static_cast<time_t>(now);
254     tp->tv_nsec = static_cast<long int>((now - tp->tv_sec) * 1e9);
255   }
256   if (smpi_wtime_sleep > 0)
257     simgrid::s4u::this_actor::sleep_for(smpi_wtime_sleep);
258   smpi_bench_begin();
259   return 0;
260 }
261 #endif
262
263 double smpi_mpi_wtime()
264 {
265   double time;
266   if (smpi_process()->initialized() && not smpi_process()->finalized() && not smpi_process()->sampling()) {
267     smpi_bench_end();
268     time = SIMIX_get_clock();
269     if (smpi_wtime_sleep > 0)
270       simgrid::s4u::this_actor::sleep_for(smpi_wtime_sleep);
271     smpi_bench_begin();
272   } else {
273     time = SIMIX_get_clock();
274   }
275   return time;
276 }
277
278 extern double sg_surf_precision;
279 unsigned long long smpi_rastro_resolution ()
280 {
281   smpi_bench_end();
282   double resolution = (1/sg_surf_precision);
283   smpi_bench_begin();
284   return static_cast<unsigned long long>(resolution);
285 }
286
287 unsigned long long smpi_rastro_timestamp ()
288 {
289   smpi_bench_end();
290   double now = SIMIX_get_clock();
291
292   unsigned long long sec = static_cast<unsigned long long>(now);
293   unsigned long long pre = (now - sec) * smpi_rastro_resolution();
294   smpi_bench_begin();
295   return static_cast<unsigned long long>(sec) * smpi_rastro_resolution() + pre;
296 }
297
298 /* ****************************** Functions related to the SMPI_SAMPLE_ macros ************************************/
299 namespace {
300 class SampleLocation : public std::string {
301 public:
302   SampleLocation(bool global, const char* file, int line) : std::string(std::string(file) + ":" + std::to_string(line))
303   {
304     if (not global)
305       this->append(":" + std::to_string(simgrid::s4u::this_actor::get_pid()));
306   }
307 };
308
309 class LocalData {
310 public:
311   double threshold; /* maximal stderr requested (if positive) */
312   double relstderr; /* observed stderr so far */
313   double mean;      /* mean of benched times, to be used if the block is disabled */
314   double sum;       /* sum of benched times (to compute the mean and stderr) */
315   double sum_pow2;  /* sum of the square of the benched times (to compute the stderr) */
316   int iters;        /* amount of requested iterations */
317   int count;        /* amount of iterations done so far */
318   bool benching;    /* true: we are benchmarking; false: we have enough data, no bench anymore */
319
320   bool need_more_benchs() const;
321 };
322
323 bool LocalData::need_more_benchs() const
324 {
325   bool res = (count < iters) || (threshold > 0.0 && (count < 2 ||          // not enough data
326                                                      relstderr > threshold // stderr too high yet
327                                                      ));
328   XBT_DEBUG("%s (count:%d iter:%d stderr:%f thres:%f mean:%fs)",
329             (res ? "need more data" : "enough benchs"), count, iters, relstderr, threshold, mean);
330   return res;
331 }
332
333 std::unordered_map<SampleLocation, LocalData, std::hash<std::string>> samples;
334 }
335
336 void smpi_sample_1(int global, const char *file, int line, int iters, double threshold)
337 {
338   SampleLocation loc(global, file, line);
339   if (not smpi_process()->sampling()) { /* Only at first call when benchmarking, skip for next ones */
340     smpi_bench_end();     /* Take time from previous, unrelated computation into account */
341     smpi_process()->set_sampling(1);
342   }
343
344   auto insert = samples.emplace(loc, LocalData{
345                                          threshold, // threshold
346                                          0.0,       // relstderr
347                                          0.0,       // mean
348                                          0.0,       // sum
349                                          0.0,       // sum_pow2
350                                          iters,     // iters
351                                          0,         // count
352                                          true       // benching (if we have no data, we need at least one)
353                                      });
354   LocalData& data = insert.first->second;
355   if (insert.second) {
356     XBT_DEBUG("XXXXX First time ever on benched nest %s.", loc.c_str());
357     xbt_assert(threshold > 0 || iters > 0,
358         "You should provide either a positive amount of iterations to bench, or a positive maximal stderr (or both)");
359   } else {
360     if (data.iters != iters || data.threshold != threshold) {
361       XBT_ERROR("Asked to bench block %s with different settings %d, %f is not %d, %f. "
362                 "How did you manage to give two numbers at the same line??",
363                 loc.c_str(), data.iters, data.threshold, iters, threshold);
364       THROW_IMPOSSIBLE;
365     }
366
367     // if we already have some data, check whether sample_2 should get one more bench or whether it should emulate
368     // the computation instead
369     data.benching = data.need_more_benchs();
370     XBT_DEBUG("XXXX Re-entering the benched nest %s. %s", loc.c_str(),
371               (data.benching ? "more benching needed" : "we have enough data, skip computes"));
372   }
373 }
374
375 int smpi_sample_2(int global, const char *file, int line, int iter_count)
376 {
377   SampleLocation loc(global, file, line);
378
379   XBT_DEBUG("sample2 %s %d", loc.c_str(), iter_count);
380   auto sample = samples.find(loc);
381   if (sample == samples.end())
382     xbt_die("Y U NO use SMPI_SAMPLE_* macros? Stop messing directly with smpi_sample_* functions!");
383   LocalData& data = sample->second;
384
385   if (data.benching) {
386     // we need to run a new bench
387     XBT_DEBUG("benchmarking: count:%d iter:%d stderr:%f thres:%f; mean:%f; total:%f",
388               data.count, data.iters, data.relstderr, data.threshold, data.mean, data.sum);
389     smpi_bench_begin();
390   } else {
391     // Enough data, no more bench (either we got enough data from previous visits to this benched nest, or we just
392     //ran one bench and need to bail out now that our job is done). Just sleep instead
393     if (not data.need_more_benchs()){
394       XBT_DEBUG("No benchmark (either no need, or just ran one): count >= iter (%d >= %d) or stderr<thres (%f<=%f). "
395               "Mean is %f, will be injected %d times",
396               data.count, data.iters, data.relstderr, data.threshold, data.mean, iter_count);
397               
398       //we ended benchmarking, let's inject all the time, now, and fast forward out of the loop.
399       smpi_process()->set_sampling(0);
400       smpi_execute(data.mean*iter_count);
401       smpi_bench_begin();
402       return 0;
403     } else {
404       XBT_DEBUG("Skipping - Benchmark already performed - accumulating time");
405       xbt_os_threadtimer_start(smpi_process()->timer());
406     }
407   }
408   return 1;
409 }
410
411 void smpi_sample_3(int global, const char *file, int line)
412 {
413   SampleLocation loc(global, file, line);
414
415   XBT_DEBUG("sample3 %s", loc.c_str());
416   auto sample = samples.find(loc);
417   if (sample == samples.end())
418     xbt_die("Y U NO use SMPI_SAMPLE_* macros? Stop messing directly with smpi_sample_* functions!");
419   LocalData& data = sample->second;
420
421   if (not data.benching)
422     THROW_IMPOSSIBLE;
423
424   // ok, benchmarking this loop is over
425   xbt_os_threadtimer_stop(smpi_process()->timer());
426
427   // update the stats
428   data.count++;
429   double period  = xbt_os_timer_elapsed(smpi_process()->timer());
430   data.sum      += period;
431   data.sum_pow2 += period * period;
432   double n       = data.count;
433   data.mean      = data.sum / n;
434   data.relstderr = sqrt((data.sum_pow2 / n - data.mean * data.mean) / n) / data.mean;
435
436   XBT_DEBUG("Average mean after %d steps is %f, relative standard error is %f (sample was %f)",
437             data.count, data.mean, data.relstderr, period);
438
439   // That's enough for now, prevent sample_2 to run the same code over and over
440   data.benching = false;
441 }
442
443 int smpi_sample_exit(int global, const char *file, int line, int iter_count){
444   if (smpi_process()->sampling()){
445     SampleLocation loc(global, file, line);
446
447     XBT_DEBUG("sample exit %s", loc.c_str());
448     auto sample = samples.find(loc);
449     if (sample == samples.end())
450       xbt_die("Y U NO use SMPI_SAMPLE_* macros? Stop messing directly with smpi_sample_* functions!");
451     LocalData& data = sample->second;
452   
453     if (smpi_process()->sampling()){//end of loop, but still sampling needed
454         smpi_process()->set_sampling(0);
455         smpi_execute(data.mean*iter_count);
456         smpi_bench_begin();
457     }
458   }
459   return 0;
460 }
461
462 smpi_trace_call_location_t* smpi_trace_get_call_location()
463 {
464   return smpi_process()->call_location();
465 }
466
467 void smpi_trace_set_call_location(const char* file, const int line)
468 {
469   smpi_trace_call_location_t* loc = smpi_process()->call_location();
470
471   loc->previous_filename   = loc->filename;
472   loc->previous_linenumber = loc->linenumber;
473   loc->filename            = file;
474   loc->linenumber          = line;
475 }
476
477 /** Required for Fortran bindings */
478 void smpi_trace_set_call_location_(const char* file, int* line)
479 {
480   smpi_trace_set_call_location(file, *line);
481 }
482
483 /** Required for Fortran if -fsecond-underscore is activated */
484 void smpi_trace_set_call_location__(const char* file, int* line)
485 {
486   smpi_trace_set_call_location(file, *line);
487 }
488
489 void smpi_bench_destroy()
490 {
491   samples.clear();
492 }
493
494 int smpi_getopt_long_only (int argc,  char *const *argv,  const char *options,
495                       const struct option * long_options, int *opt_index)
496 {
497   if (smpi_process())
498     optind = smpi_process()->get_optind();
499   int ret = getopt_long_only (argc,  argv,  options, long_options, opt_index);
500   if (smpi_process())
501     smpi_process()->set_optind(optind);
502   return ret;
503 }
504
505 int smpi_getopt_long (int argc,  char *const *argv,  const char *options,
506                       const struct option * long_options, int *opt_index)
507 {
508   if (smpi_process())
509     optind = smpi_process()->get_optind();
510   int ret = getopt_long (argc,  argv,  options, long_options, opt_index);
511   if (smpi_process())
512     smpi_process()->set_optind(optind);
513   return ret;
514 }
515
516 int smpi_getopt (int argc,  char *const *argv,  const char *options)
517 {
518   if (smpi_process())
519     optind = smpi_process()->get_optind();
520   int ret = getopt (argc,  argv,  options);
521   if (smpi_process())
522     smpi_process()->set_optind(optind);
523   return ret;
524 }