Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add new entry in Release_Notes.
[simgrid.git] / src / plugins / host_dvfs.cpp
1 /* Copyright (c) 2010-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 <simgrid/plugins/dvfs.h>
7 #include <simgrid/plugins/load.h>
8 #include <simgrid/s4u/Actor.hpp>
9 #include <simgrid/s4u/Host.hpp>
10 #include <simgrid/s4u/VirtualMachine.hpp>
11 #include <xbt/asserts.h>
12 #include <xbt/config.hpp>
13
14 #include "src/internal_config.h" // HAVE_SMPI
15 #include "src/kernel/activity/CommImpl.hpp"
16 #include "src/kernel/resource/NetworkModel.hpp"
17 #include "src/simgrid/module.hpp"
18 #if HAVE_SMPI
19 #include "src/smpi/include/smpi_request.hpp"
20 #include "src/smpi/plugins/ampi/ampi.hpp"
21 #endif
22
23 #include <boost/algorithm/string.hpp>
24 #include <string_view>
25
26 SIMGRID_REGISTER_PLUGIN(host_dvfs, "Dvfs support", &sg_host_dvfs_plugin_init)
27
28 static simgrid::config::Flag<double>
29     cfg_sampling_rate("plugin/dvfs/sampling-rate",
30                       "How often should the dvfs plugin check whether the frequency needs to be changed?", 0.1,
31                       [](double val) {
32                         if (val != 0.1)
33                           sg_host_dvfs_plugin_init();
34                       });
35
36 static simgrid::config::Flag<std::string> cfg_governor("plugin/dvfs/governor",
37                                                        "Which Governor should be used that adapts the CPU frequency?",
38                                                        "performance",
39
40                                                        std::map<std::string, std::string, std::less<>>({
41 #if HAVE_SMPI
42                                                          {"adagio", "TODO: Doc"},
43 #endif
44                                                              {"conservative", "TODO: Doc"}, {"ondemand", "TODO: Doc"},
45                                                              {"performance", "TODO: Doc"}, {"powersave", "TODO: Doc"},
46                                                        }),
47
48                                                        [](std::string_view val) {
49                                                          if (val != "performance")
50                                                            sg_host_dvfs_plugin_init();
51                                                        });
52
53 static simgrid::config::Flag<int>
54     cfg_min_pstate("plugin/dvfs/min-pstate",
55                    "Which pstate is the minimum (and hence fastest) pstate for this governor?", 0);
56
57 static constexpr int MAX_PSTATE_NOT_LIMITED = -1;
58 static simgrid::config::Flag<int>
59     cfg_max_pstate("plugin/dvfs/max-pstate",
60                    "Which pstate is the maximum (and hence slowest) pstate for this governor?", MAX_PSTATE_NOT_LIMITED);
61
62 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(host_dvfs, kernel, "Logging specific to the HostDvfs plugin");
63
64 namespace simgrid::plugin::dvfs {
65
66 /**
67  *  Add this to your host tag:
68  *    - \<prop id="plugin/dvfs/governor" value="performance" /\>
69  *
70  *  Valid values as of now are: performance, powersave, ondemand, conservative
71  *  It doesn't matter if you use uppercase or lowercase.
72  *
73  *  For the sampling rate, use this:
74  *
75  *    - \<prop id="plugin/dvfs/sampling-rate" value="2" /\>
76  *
77  *  This will run the update() method of the specified governor every 2 seconds
78  *  on that host.
79  *
80  *  These properties can also be used within the \<config\> tag to configure
81  *  these values globally. Using them within the \<host\> will overwrite this
82  *  global configuration
83  */
84 class Governor {
85   simgrid::s4u::Host* const host_;
86   double sampling_rate_;
87   unsigned long min_pstate = cfg_min_pstate; //< Never use a pstate less than this one
88   unsigned long max_pstate = cfg_max_pstate; //< Never use a pstate larger than this one
89
90 public:
91   explicit Governor(simgrid::s4u::Host* ptr)
92       : host_(ptr)
93   {
94     if (cfg_max_pstate == MAX_PSTATE_NOT_LIMITED)
95       max_pstate = host_->get_pstate_count() - 1;
96     init();
97   }
98   virtual ~Governor() = default;
99   virtual std::string get_name() const = 0;
100   simgrid::s4u::Host* get_host() const { return host_; }
101   unsigned long get_min_pstate() const { return min_pstate; }
102   unsigned long get_max_pstate() const { return max_pstate; }
103
104   void init()
105   {
106     if (const char* local_sampling_rate_config = host_->get_property(cfg_sampling_rate.get_name())) {
107       sampling_rate_ = std::stod(local_sampling_rate_config);
108     } else {
109       sampling_rate_ = cfg_sampling_rate;
110     }
111     if (const char* local_min_pstate_config = host_->get_property(cfg_min_pstate.get_name())) {
112       min_pstate = std::stoul(local_min_pstate_config);
113     }
114
115     if (const char* local_max_pstate_config = host_->get_property(cfg_max_pstate.get_name())) {
116       max_pstate = std::stoul(local_max_pstate_config);
117     }
118     xbt_assert(max_pstate <= host_->get_pstate_count() - 1, "Value for max_pstate too large!");
119     xbt_assert(min_pstate <= max_pstate, "min_pstate is larger than max_pstate!");
120   }
121
122   virtual void update()         = 0;
123   double get_sampling_rate() const { return sampling_rate_; }
124 };
125
126 /**
127  * The linux kernel doc describes this governor as follows:
128  * https://www.kernel.org/doc/Documentation/cpu-freq/governors.txt
129  *
130  * > The CPUfreq governor "performance" sets the CPU statically to the
131  * > highest frequency within the borders of scaling_min_freq and
132  * > scaling_max_freq.
133  *
134  * We do not support scaling_min_freq/scaling_max_freq -- we just pick the lowest frequency.
135  */
136 class Performance : public Governor {
137 public:
138   using Governor::Governor;
139   std::string get_name() const override { return "Performance"; }
140
141   void update() override { get_host()->set_pstate(get_min_pstate()); }
142 };
143
144 /**
145  * The linux kernel doc describes this governor as follows:
146  * https://www.kernel.org/doc/Documentation/cpu-freq/governors.txt
147  *
148  * > The CPUfreq governor "powersave" sets the CPU statically to the
149  * > lowest frequency within the borders of scaling_min_freq and
150  * > scaling_max_freq.
151  *
152  * We do not support scaling_min_freq/scaling_max_freq -- we just pick the lowest frequency.
153  */
154 class Powersave : public Governor {
155 public:
156   using Governor::Governor;
157   std::string get_name() const override { return "Powersave"; }
158
159   void update() override { get_host()->set_pstate(get_max_pstate()); }
160 };
161
162 /**
163  * The linux kernel doc describes this governor as follows:
164  * https://www.kernel.org/doc/Documentation/cpu-freq/governors.txt
165  *
166  * > The CPUfreq governor "ondemand" sets the CPU frequency depending on the
167  * > current system load. [...] when triggered, cpufreq checks
168  * > the CPU-usage statistics over the last period and the governor sets the
169  * > CPU accordingly.
170  */
171 class OnDemand : public Governor {
172   /**
173    * See https://elixir.bootlin.com/linux/v4.15.4/source/drivers/cpufreq/cpufreq_ondemand.c
174    * DEF_FREQUENCY_UP_THRESHOLD and od_update()
175    */
176   double freq_up_threshold_ = 0.80;
177
178 public:
179   using Governor::Governor;
180   std::string get_name() const override { return "OnDemand"; }
181
182   void update() override
183   {
184     double load = get_host()->get_core_count() * sg_host_get_avg_load(get_host());
185     sg_host_load_reset(get_host()); // Only consider the period between two calls to this method!
186
187     if (load > freq_up_threshold_) {
188       get_host()->set_pstate(get_min_pstate()); /* Run at max. performance! */
189       XBT_INFO("Load: %f > threshold: %f --> changed to pstate %lu", load, freq_up_threshold_, get_min_pstate());
190     } else {
191       /* The actual implementation uses a formula here: (See Kernel file cpufreq_ondemand.c:158)
192        *
193        *    freq_next = min_f + load * (max_f - min_f) / 100
194        *
195        * So they assume that frequency increases by 100 MHz. We will just use
196        * lowest_pstate - load*pstatesCount()
197        */
198       // Load is now < freq_up_threshold; exclude pstate 0 (the fastest)
199       // because pstate 0 can only be selected if load > freq_up_threshold_
200       auto new_pstate = get_max_pstate() - static_cast<unsigned long>(load) * (get_max_pstate() + 1);
201       if (new_pstate < get_min_pstate())
202         new_pstate = get_min_pstate();
203       get_host()->set_pstate(new_pstate);
204
205       XBT_DEBUG("Load: %f < threshold: %f --> changed to pstate %lu", load, freq_up_threshold_, new_pstate);
206     }
207   }
208 };
209
210 /**
211  * This is the conservative governor, which is very similar to the
212  * OnDemand governor. The Linux Kernel Documentation describes it
213  * very well, see https://www.kernel.org/doc/Documentation/cpu-freq/governors.txt:
214  *
215  * > The CPUfreq governor "conservative", much like the "ondemand"
216  * > governor, sets the CPU frequency depending on the current usage.  It
217  * > differs in behavior in that it gracefully increases and decreases the
218  * > CPU speed rather than jumping to max speed the moment there is any load
219  * > on the CPU. This behavior is more suitable in a battery powered
220  * > environment.
221  */
222 class Conservative : public Governor {
223   double freq_up_threshold_   = .8;
224   double freq_down_threshold_ = .2;
225
226 public:
227   using Governor::Governor;
228   std::string get_name() const override { return "Conservative"; }
229
230   void update() override
231   {
232     double load = get_host()->get_core_count() * sg_host_get_avg_load(get_host());
233     unsigned long pstate = get_host()->get_pstate();
234     sg_host_load_reset(get_host()); // Only consider the period between two calls to this method!
235
236     if (load > freq_up_threshold_) {
237       if (pstate != get_min_pstate()) {
238         get_host()->set_pstate(pstate - 1);
239         XBT_INFO("Load: %f > threshold: %f -> increasing performance to pstate %lu", load, freq_up_threshold_,
240                  pstate - 1);
241       } else {
242         XBT_DEBUG("Load: %f > threshold: %f -> but cannot speed up even more, already in highest pstate %lu", load,
243                   freq_up_threshold_, pstate);
244       }
245     } else if (load < freq_down_threshold_) {
246       if (pstate != get_max_pstate()) { // Are we in the slowest pstate already?
247         get_host()->set_pstate(pstate + 1);
248         XBT_INFO("Load: %f < threshold: %f -> slowing down to pstate %lu", load, freq_down_threshold_, pstate + 1);
249       } else {
250         XBT_DEBUG("Load: %f < threshold: %f -> cannot slow down even more, already in slowest pstate %lu", load,
251                   freq_down_threshold_, pstate);
252       }
253     }
254   }
255 };
256
257 #if HAVE_SMPI
258 class Adagio : public Governor {
259   unsigned long best_pstate = 0;
260   double start_time         = 0;
261   double comp_counter       = 0;
262   double comp_timer         = 0;
263
264   std::vector<std::vector<double>> rates; // Each host + all frequencies of that host
265
266   unsigned int task_id   = 0;
267   bool iteration_running = false; /*< Are we currently between iteration_in and iteration_out calls? */
268
269 public:
270   explicit Adagio(simgrid::s4u::Host* ptr)
271       : Governor(ptr), rates(100, std::vector<double>(ptr->get_pstate_count(), 0.0))
272   {
273     simgrid::smpi::plugin::ampi::on_iteration_in.connect([this](simgrid::s4u::Actor const& actor) {
274       // Every instance of this class subscribes to this event, so one per host
275       // This means that for any actor, all 'hosts' are normally notified of these
276       // changes, even those who don't currently run the actor 'proc_id'.
277       // -> Let's check if this signal call is for us!
278       if (get_host() == actor.get_host()) {
279         iteration_running = true;
280       }
281     });
282     simgrid::smpi::plugin::ampi::on_iteration_out.connect([this](simgrid::s4u::Actor const& actor) {
283       if (get_host() == actor.get_host()) {
284         iteration_running = false;
285         task_id           = 0;
286       }
287     });
288     simgrid::s4u::Exec::on_start_cb([this](simgrid::s4u::Exec const& activity) {
289       if (activity.get_host() == get_host())
290         pre_task();
291     });
292     simgrid::s4u::Exec::on_completion_cb([this](simgrid::s4u::Exec const& exec) {
293       // For more than one host (not yet supported), we can access the host via
294       // simcalls_.front()->issuer->get_iface()->get_host()
295       if (exec.get_host() == get_host() && iteration_running) {
296         comp_timer += exec.get_finish_time() - exec.get_start_time();
297       }
298     });
299     // FIXME I think that this fires at the same time for all hosts, so when the src sends something,
300     // the dst will be notified even though it didn't even arrive at the recv yet
301     simgrid::s4u::Comm::on_start_cb([this](const s4u::Comm& comm) {
302       if ((get_host() == comm.get_sender()->get_host() || get_host() == comm.get_receiver()->get_host()) &&
303            iteration_running) {
304         post_task();
305       }
306     });
307   }
308
309   std::string get_name() const override { return "Adagio"; }
310
311   void pre_task()
312   {
313     sg_host_load_reset(get_host());
314     comp_counter = sg_host_get_computed_flops(get_host()); // Should be 0 because of the reset
315     comp_timer   = 0;
316     start_time   = simgrid::s4u::Engine::get_clock();
317     if (rates.size() <= task_id)
318       rates.resize(task_id + 5, std::vector<double>(get_host()->get_pstate_count(), 0.0));
319     if (rates[task_id][best_pstate] == 0)
320       best_pstate = 0;
321     get_host()->set_pstate(best_pstate); // Load our schedule
322     XBT_DEBUG("Set pstate to %lu", best_pstate);
323   }
324
325   void post_task()
326   {
327     double computed_flops = sg_host_get_computed_flops(get_host()) - comp_counter;
328     double target_time    = (simgrid::s4u::Engine::get_clock() - start_time);
329     target_time           = target_time * 99.0 / 100.0; // FIXME We account for t_copy arbitrarily with 1%
330                                                         // -- this needs to be fixed
331
332     bool is_initialized         = rates[task_id][best_pstate] != 0;
333     rates[task_id][best_pstate] = computed_flops / comp_timer;
334     if (not is_initialized) {
335       for (unsigned long i = 1; i < get_host()->get_pstate_count(); i++) {
336         rates[task_id][i] = rates[task_id][0] * (get_host()->get_pstate_speed(i) / get_host()->get_speed());
337       }
338     }
339
340     for (unsigned long pstate = get_host()->get_pstate_count() - 1; pstate != 0; pstate--) {
341       if (computed_flops / rates[task_id][pstate] <= target_time) {
342         // We just found the pstate we want to use!
343         best_pstate = pstate;
344         break;
345       }
346     }
347     task_id++;
348   }
349
350   void update() override {}
351 };
352 #endif
353 } // namespace simgrid::plugin::dvfs
354
355 /* **************************** events  callback *************************** */
356 static void on_host_added(simgrid::s4u::Host& host)
357 {
358   if (dynamic_cast<simgrid::s4u::VirtualMachine*>(&host)) // Ignore virtual machines
359     return;
360
361   std::string name              = "dvfs-daemon-" + host.get_name();
362   simgrid::s4u::ActorPtr daemon = simgrid::s4u::Actor::create(name.c_str(), &host, []() {
363     /**
364      * This lambda function is the function the actor (daemon) will execute
365      * all the time - in the case of the dvfs plugin, this controls when to
366      * lower/raise the frequency.
367      */
368     simgrid::s4u::ActorPtr daemon_proc = simgrid::s4u::Actor::self();
369
370     XBT_DEBUG("DVFS process on %s is a daemon: %d", daemon_proc->get_host()->get_cname(), daemon_proc->is_daemon());
371
372     std::string dvfs_governor;
373     if (const char* host_conf = daemon_proc->get_host()->get_property("plugin/dvfs/governor")) {
374       dvfs_governor = host_conf;
375       boost::algorithm::to_lower(dvfs_governor);
376     } else {
377       dvfs_governor = cfg_governor;
378       boost::algorithm::to_lower(dvfs_governor);
379     }
380
381     auto governor = [&dvfs_governor, &daemon_proc]() -> std::unique_ptr<simgrid::plugin::dvfs::Governor> {
382       if (dvfs_governor == "conservative")
383         return std::make_unique<simgrid::plugin::dvfs::Conservative>(daemon_proc->get_host());
384       if (dvfs_governor == "ondemand")
385         return std::make_unique<simgrid::plugin::dvfs::OnDemand>(daemon_proc->get_host());
386 #if HAVE_SMPI
387       if (dvfs_governor == "adagio")
388         return std::make_unique<simgrid::plugin::dvfs::Adagio>(daemon_proc->get_host());
389 #endif
390       if (dvfs_governor == "powersave")
391         return std::make_unique<simgrid::plugin::dvfs::Powersave>(daemon_proc->get_host());
392       if (dvfs_governor != "performance")
393         XBT_CRITICAL("No governor specified for host %s, falling back to Performance",
394                      daemon_proc->get_host()->get_cname());
395       return std::make_unique<simgrid::plugin::dvfs::Performance>(daemon_proc->get_host());
396     }();
397
398     while (true) {
399       // Sleep *before* updating; important for startup (i.e., t = 0).
400       // In the beginning, we want to go with the pstates specified in the platform file
401       // (so we sleep first)
402       simgrid::s4u::this_actor::sleep_for(governor->get_sampling_rate());
403       governor->update();
404       XBT_DEBUG("Governor (%s) just updated!", governor->get_name().c_str());
405     }
406
407     XBT_WARN("I should have never reached this point: daemons should be killed when all regular processes are done");
408     return 0;
409   });
410
411   // This call must be placed in this function. Otherwise, the daemonize() call comes too late and
412   // SMPI will take this process as an MPI process!
413   daemon->daemonize();
414 }
415
416 /* **************************** Public interface *************************** */
417
418 /**
419  * @brief Initializes the HostDvfs plugin
420  * @details The HostDvfs plugin provides an API to get the current load of each host.
421  */
422 void sg_host_dvfs_plugin_init()
423 {
424   static bool inited = false;
425   if (inited)
426     return;
427   inited = true;
428
429   sg_host_load_plugin_init();
430
431   simgrid::s4u::Host::on_creation_cb(&on_host_added);
432 }