Logo AND Algorithmique Numérique Distribuée

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