1 /* Copyright (c) 2007-2023. The SimGrid Team. All rights reserved. */
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. */
7 #include "simgrid/host.h"
8 #include "simgrid/modelchecker.h"
9 #include "simgrid/s4u/Engine.hpp"
10 #include "simgrid/s4u/Exec.hpp"
11 #include "smpi_comm.hpp"
12 #include "smpi_utils.hpp"
13 #include "src/internal_config.h"
14 #include "src/kernel/lmm/System.hpp" // sg_precision_timing
15 #include "src/mc/mc_replay.hpp"
16 #include "xbt/config.hpp"
17 #include "xbt/file.hpp"
20 #include "src/smpi/include/smpi_actor.hpp"
25 #include <unordered_map>
31 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_bench, smpi, "Logging specific to SMPI (benchmarking)");
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 */);
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())
47 smpi_switch_data_segment(simgrid::s4u::Actor::self());
50 void smpi_execute_flops(double flops)
52 private_execute_flops(flops);
55 void smpi_execute(double duration)
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());
61 XBT_DEBUG("Real computation took %g while option smpi/cpu-threshold is set to %g => ignore it", duration,
62 smpi_cfg_cpu_thresh());
66 void smpi_execute_benched(double duration)
68 const SmpiBenchGuard suspend_bench;
69 double speed = sg_host_get_speed(sg_host_self());
70 smpi_execute_flops(duration*speed);
73 void smpi_execute_flops_benched(double flops) {
74 const SmpiBenchGuard suspend_bench;
75 smpi_execute_flops(flops);
78 void smpi_bench_begin()
80 smpi_switch_data_segment(simgrid::s4u::Actor::self());
82 if (MC_is_active() || MC_record_replay_is_active())
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).");
94 xbt_os_threadtimer_start(smpi_process()->timer());
97 double smpi_adjust_comp_speed(){
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;
110 void smpi_bench_end()
112 if (MC_is_active() || MC_record_replay_is_active())
115 xbt_os_timer_t timer = smpi_process()->timer();
116 xbt_os_threadtimer_stop(timer);
120 * An MPI function has been called and now is the right time to update
121 * our PAPI counters for this process.
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());
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];
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.");
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());
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();
154 for (auto const& [counter, value] : counter_data) {
155 container->get_variable(counter)->set_event(simgrid::s4u::Engine::get_clock(), static_cast<double>(value));
160 simgrid::smpi::utils::add_benched_time(xbt_os_timer_elapsed(timer));
163 /* Private sleep function used by smpi_sleep(), smpi_usleep() and friends */
164 static void private_sleep(double secs)
166 const SmpiBenchGuard suspend_bench;
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);
175 unsigned int smpi_sleep(unsigned int secs)
177 if (not smpi_process())
183 int smpi_usleep(useconds_t usecs)
185 if (not smpi_process())
186 return usleep(usecs);
187 private_sleep(static_cast<double>(usecs) / 1e6);
191 #if _POSIX_TIMERS > 0
192 int smpi_nanosleep(const struct timespec* tp, struct timespec* t)
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);
201 int smpi_gettimeofday(struct timeval* tv, struct timezone* tz)
203 if (not smpi_process()->initialized() || smpi_process()->finalized() || smpi_process()->sampling())
204 return gettimeofday(tv, tz);
206 const SmpiBenchGuard suspend_bench;
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
214 if (smpi_wtime_sleep > 0)
215 simgrid::s4u::this_actor::sleep_for(smpi_wtime_sleep);
219 #if _POSIX_TIMERS > 0
220 int smpi_clock_gettime(clockid_t clk_id, struct timespec* tp)
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);
241 double smpi_mpi_wtime()
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);
250 time = simgrid::s4u::Engine::get_clock();
255 // Used by Akypuera (https://github.com/schnorr/akypuera)
256 unsigned long long smpi_rastro_resolution ()
258 const SmpiBenchGuard suspend_bench;
259 return static_cast<unsigned long long>(1.0 / sg_precision_timing);
262 unsigned long long smpi_rastro_timestamp ()
264 const SmpiBenchGuard suspend_bench;
265 return static_cast<unsigned long long>(simgrid::s4u::Engine::get_clock() / sg_precision_timing);
268 /* ****************************** Functions related to the SMPI_SAMPLE_ macros ************************************/
270 class SampleLocation : public std::string {
272 SampleLocation(bool global, const char* file, const char* tag) : std::string(std::string(file) + ":" + std::string(tag))
275 this->append(":" + std::to_string(simgrid::s4u::this_actor::get_pid()));
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 */
290 bool need_more_benchs() const;
293 bool LocalData::need_more_benchs() const
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);
302 std::unordered_map<SampleLocation, LocalData, std::hash<std::string>> samples;
305 int smpi_sample_cond(int global, const char* file, const char* tag, int iters, double threshold, int iter_count)
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);
313 auto [sample, inserted] = samples.try_emplace(loc,
315 threshold, // threshold
322 true // benching (if we have no data, we need at least one)
324 LocalData& data = sample->second;
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)");
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);
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"));
345 XBT_DEBUG("sample cond %s %d", loc.c_str(), iter_count);
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);
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);
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);
365 XBT_DEBUG("Skipping - Benchmark already performed - accumulating time");
366 xbt_os_threadtimer_start(smpi_process()->timer());
372 void smpi_sample_iter(int global, const char* file, const char* tag)
374 SampleLocation loc(global, file, tag);
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);
383 // ok, benchmarking this loop is over
384 xbt_os_threadtimer_stop(smpi_process()->timer());
388 double period = xbt_os_timer_elapsed(smpi_process()->timer());
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;
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);
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);
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!");
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);
418 smpi_trace_call_location_t* smpi_trace_get_call_location()
420 return smpi_process()->call_location();
423 void smpi_trace_set_call_location(const char* file, const int line, const char* call_name)
425 smpi_trace_call_location_t* loc = smpi_process()->call_location();
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();
432 loc->filename = file;
433 loc->linenumber = line;
434 loc->func_call = call_name;
437 /** Required for Fortran bindings */
438 void smpi_trace_set_call_location_(const char* file, const int* line, const char* call_name)
440 smpi_trace_set_call_location(file, *line, call_name);
443 /** Required for Fortran if -fsecond-underscore is activated */
444 void smpi_trace_set_call_location__(const char* file, const int* line, const char* call_name)
446 smpi_trace_set_call_location(file, *line, call_name);
449 void smpi_bench_destroy()
454 int smpi_getopt_long_only (int argc, char *const *argv, const char *options,
455 const struct option * long_options, int *opt_index)
458 optind = smpi_process()->get_optind();
459 int ret = getopt_long_only (argc, argv, options, long_options, opt_index);
461 smpi_process()->set_optind(optind);
465 int smpi_getopt_long (int argc, char *const *argv, const char *options,
466 const struct option * long_options, int *opt_index)
469 optind = smpi_process()->get_optind();
470 int ret = getopt_long (argc, argv, options, long_options, opt_index);
472 smpi_process()->set_optind(optind);
476 int smpi_getopt (int argc, char *const *argv, const char *options)
479 optind = smpi_process()->get_optind();
480 int ret = getopt (argc, argv, options);
482 smpi_process()->set_optind(optind);
487 return static_cast<pid_t>(simgrid::s4u::this_actor::get_pid());