Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Update .mailmap.
[simgrid.git] / src / kernel / resource / models / cpu_ti.cpp
1 /* Copyright (c) 2013-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 "cpu_ti.hpp"
7 #include "simgrid/kernel/routing/NetZoneImpl.hpp"
8 #include "simgrid/s4u/Engine.hpp"
9 #include "src/kernel/EngineImpl.hpp"
10 #include "src/kernel/resource/profile/Event.hpp"
11 #include "src/kernel/resource/profile/Profile.hpp"
12 #include "src/simgrid/math_utils.h"
13 #include "xbt/asserts.h"
14
15 #include <algorithm>
16 #include <memory>
17
18 constexpr double EPSILON = 0.000000001;
19
20 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(cpu_ti, res_cpu, "CPU resource, Trace Integration model");
21
22 namespace simgrid::kernel::resource {
23
24 /*********
25  * Trace *
26  *********/
27
28 CpuTiProfile::CpuTiProfile(const profile::Profile* profile)
29 {
30   double integral                                = 0;
31   double time                                    = 0;
32   double prev_value                              = 1;
33   const std::vector<profile::DatedValue>& events = profile->get_event_list();
34   xbt_assert(not events.empty());
35   unsigned long nb_points = events.size() + 1;
36   time_points_.reserve(nb_points);
37   integral_.reserve(nb_points);
38   for (auto const& val : events) {
39     time += val.date_;
40     integral += val.date_ * prev_value;
41     time_points_.push_back(time);
42     integral_.push_back(integral);
43     prev_value = val.value_;
44   }
45
46   double delay = profile->get_repeat_delay() + events.at(0).date_;
47
48   xbt_assert(events.back().value_ == prev_value, "Profiles need to end as they start");
49   time += delay;
50   integral += delay * prev_value;
51
52   time_points_.push_back(time);
53   integral_.push_back(integral);
54 }
55
56 /**
57  * @brief Integrate trace
58  *
59  * Wrapper around profile_->integrate_simple() to get
60  * the cyclic effect.
61  *
62  * @param a      Begin of interval
63  * @param b      End of interval
64  * @return the integrate value. -1 if an error occurs.
65  */
66 double CpuTiTmgr::integrate(double a, double b) const
67 {
68   xbt_assert(a >= 0.0 && a <= b,
69              "Error, invalid integration interval [%.2f,%.2f]. You probably have a task executing with negative "
70              "computation amount. Check your code.",
71              a, b);
72   if (fabs(a - b) < EPSILON)
73     return 0.0;
74
75   if (type_ == Type::FIXED) {
76     return (b - a) * value_;
77   }
78
79   double a_index;
80   if (fabs(ceil(a / last_time_) - a / last_time_) < EPSILON)
81     a_index = 1 + ceil(a / last_time_);
82   else
83     a_index = ceil(a / last_time_);
84   double b_index = floor(b / last_time_);
85
86   if (a_index > b_index) { /* Same chunk */
87     return profile_->integrate_simple(a - (a_index - 1) * last_time_, b - b_index * last_time_);
88   }
89
90   double first_chunk  = profile_->integrate_simple(a - (a_index - 1) * last_time_, last_time_);
91   double middle_chunk = (b_index - a_index) * total_;
92   double last_chunk   = profile_->integrate_simple(0.0, b - b_index * last_time_);
93
94   XBT_DEBUG("first_chunk=%.2f  middle_chunk=%.2f  last_chunk=%.2f\n", first_chunk, middle_chunk, last_chunk);
95
96   return (first_chunk + middle_chunk + last_chunk);
97 }
98
99 /**
100  * @brief Auxiliary function to compute the integral between a and b.
101  *     It simply computes the integrals at point a and b and returns the difference between them.
102  * @param a  Initial point
103  * @param b  Final point
104  */
105 double CpuTiProfile::integrate_simple(double a, double b) const
106 {
107   return integrate_simple_point(b) - integrate_simple_point(a);
108 }
109
110 /**
111  * @brief Auxiliary function to compute the integral at point a.
112  * @param a        point
113  */
114 double CpuTiProfile::integrate_simple_point(double a) const
115 {
116   double integral = 0;
117   double a_aux    = a;
118   long ind        = binary_search(time_points_, a);
119   integral += integral_[ind];
120
121   XBT_DEBUG("a %f ind %ld integral %f ind + 1 %f ind %f time +1 %f time %f", a, ind, integral, integral_[ind + 1],
122             integral_[ind], time_points_[ind + 1], time_points_[ind]);
123   double_update(&a_aux, time_points_[ind], sg_precision_workamount * sg_precision_timing);
124   if (a_aux > 0)
125     integral +=
126         ((integral_[ind + 1] - integral_[ind]) / (time_points_[ind + 1] - time_points_[ind])) * (a - time_points_[ind]);
127   XBT_DEBUG("Integral a %f = %f", a, integral);
128
129   return integral;
130 }
131
132 /**
133  * @brief Computes the time needed to execute "amount" on cpu.
134  *
135  * Here, amount can span multiple trace periods
136  *
137  * @param a        Initial time
138  * @param amount  Amount to be executed
139  * @return  End time
140  */
141 double CpuTiTmgr::solve(double a, double amount) const
142 {
143   /* Fix very small negative numbers */
144   if ((a < 0.0) && (a > -EPSILON)) {
145     a = 0.0;
146   }
147   if ((amount < 0.0) && (amount > -EPSILON)) {
148     amount = 0.0;
149   }
150
151   /* Sanity checks */
152   xbt_assert(a >= 0.0 && amount >= 0.0,
153              "Error, invalid parameters [a = %.2f, amount = %.2f]. "
154              "You probably have a task executing with negative computation amount. Check your code.",
155              a, amount);
156
157   /* At this point, a and amount are positive */
158   if (amount < EPSILON)
159     return a;
160
161   /* Is the trace fixed ? */
162   if (type_ == Type::FIXED) {
163     return (a + (amount / value_));
164   }
165
166   XBT_DEBUG("amount %f total %f", amount, total_);
167   /* Reduce the problem to one where amount <= trace_total */
168   double quotient       = floor(amount / total_);
169   double reduced_amount = total_ * ((amount / total_) - floor(amount / total_));
170   double reduced_a      = a - last_time_ * static_cast<int>(floor(a / last_time_));
171
172   XBT_DEBUG("Quotient: %g reduced_amount: %f reduced_a: %f", quotient, reduced_amount, reduced_a);
173
174   /* Now solve for new_amount which is <= trace_total */
175   XBT_DEBUG("Solve integral: [%.2f, amount=%.2f]", reduced_a, reduced_amount);
176
177   double amount_till_end = integrate(reduced_a, last_time_);
178   double reduced_b       = amount_till_end > reduced_amount
179                                ? profile_->solve_simple(reduced_a, reduced_amount)
180                                : last_time_ + profile_->solve_simple(0.0, reduced_amount - amount_till_end);
181
182   /* Re-map to the original b and amount */
183   return last_time_ * floor(a / last_time_) + (quotient * last_time_) + reduced_b;
184 }
185
186 /**
187  * @brief Auxiliary function to solve integral.
188  *  It returns the date when the requested amount of flops is available
189  * @param a        Initial point
190  * @param amount  Amount of flops
191  * @return The date when amount is available.
192  */
193 double CpuTiProfile::solve_simple(double a, double amount) const
194 {
195   double integral_a = integrate_simple_point(a);
196   long ind          = binary_search(integral_, integral_a + amount);
197   double time       = time_points_[ind];
198   time += (integral_a + amount - integral_[ind]) /
199           ((integral_[ind + 1] - integral_[ind]) / (time_points_[ind + 1] - time_points_[ind]));
200
201   return time;
202 }
203
204 /**
205  * @brief Auxiliary function to update the CPU speed scale.
206  *
207  *  This function uses the trace structure to return the speed scale at the determined time a.
208  * @param a        Time
209  * @return CPU speed scale
210  */
211 double CpuTiTmgr::get_power_scale(double a) const
212 {
213   double reduced_a        = a - floor(a / last_time_) * last_time_;
214   long point              = CpuTiProfile::binary_search(profile_->get_time_points(), reduced_a);
215   profile::DatedValue val = speed_profile_->get_event_list().at(point);
216   return val.value_;
217 }
218
219 /**
220  * @brief Creates a new integration trace from a tmgr_trace_t
221  *
222  * @param  speed_trace    CPU availability trace
223  * @param  value          Percentage of CPU speed available (useful to fixed tracing)
224  * @return  Integration trace structure
225  */
226 CpuTiTmgr::CpuTiTmgr(kernel::profile::Profile* speed_profile, double value) : speed_profile_(speed_profile)
227 {
228   double total_time = 0.0;
229   profile_.reset(nullptr);
230
231   /* no availability file, fixed trace */
232   if (not speed_profile) {
233     value_ = value;
234     XBT_DEBUG("No availability trace. Constant value = %f", value);
235     return;
236   }
237
238   xbt_assert(speed_profile->is_repeating());
239
240   /* only one point available, fixed trace */
241   if (speed_profile->get_event_list().size() == 1) {
242     value_ = speed_profile->get_event_list().front().value_;
243     return;
244   }
245
246   type_ = Type::DYNAMIC;
247
248   /* count the total time of trace file */
249   for (auto const& val : speed_profile->get_event_list())
250     total_time += val.date_;
251   total_time += speed_profile->get_repeat_delay();
252
253   profile_   = std::make_unique<CpuTiProfile>(speed_profile);
254   last_time_ = total_time;
255   total_     = profile_->integrate_simple(0, total_time);
256
257   XBT_DEBUG("Total integral %f, last_time %f ", total_, last_time_);
258 }
259
260 /**
261  * @brief Binary search in array.
262  *  It returns the last point of the interval in which "a" is.
263  * @param array    Array
264  * @param a        Value to search
265  * @return Index of point
266  */
267 long CpuTiProfile::binary_search(const std::vector<double>& array, double a)
268 {
269   if (array[0] > a)
270     return 0;
271   auto pos = std::upper_bound(begin(array), end(array), a);
272   return std::distance(begin(array), pos) - 1;
273 }
274
275 /*********
276  * Model *
277  *********/
278
279 void CpuTiModel::create_pm_models()
280 {
281   auto cpu_model_pm = std::make_shared<CpuTiModel>("Cpu_TI");
282   auto* engine      = EngineImpl::get_instance();
283   engine->add_model(cpu_model_pm);
284   engine->get_netzone_root()->set_cpu_pm_model(cpu_model_pm);
285 }
286
287 CpuImpl* CpuTiModel::create_cpu(s4u::Host* host, const std::vector<double>& speed_per_pstate)
288 {
289   return (new CpuTi(host, speed_per_pstate))->set_model(this);
290 }
291
292 double CpuTiModel::next_occurring_event(double now)
293 {
294   double min_action_duration = -1;
295
296   /* iterates over modified cpus to update share resources */
297   for (auto it = std::begin(modified_cpus_); it != std::end(modified_cpus_);) {
298     CpuTi& cpu = *it;
299     ++it; // increment iterator here since the following call to ti.update_actions_finish_time() may invalidate it
300     cpu.update_actions_finish_time(now);
301   }
302
303   /* get the min next event if heap not empty */
304   if (not get_action_heap().empty())
305     min_action_duration = get_action_heap().top_date() - now;
306
307   XBT_DEBUG("Share resources, min next event date: %f", min_action_duration);
308
309   return min_action_duration;
310 }
311
312 void CpuTiModel::update_actions_state(double now, double /*delta*/)
313 {
314   while (not get_action_heap().empty() && double_equals(get_action_heap().top_date(), now, sg_precision_timing)) {
315     auto* action = static_cast<CpuTiAction*>(get_action_heap().pop());
316     XBT_DEBUG("Action %p: finish", action);
317     action->finish(Action::State::FINISHED);
318     /* update remaining amount of all actions */
319     action->cpu_->update_remaining_amount(EngineImpl::get_clock());
320   }
321 }
322
323 /************
324  * Resource *
325  ************/
326 CpuTi::CpuTi(s4u::Host* host, const std::vector<double>& speed_per_pstate) : CpuImpl(host, speed_per_pstate)
327 {
328   speed_.peak = speed_per_pstate.front();
329   XBT_DEBUG("CPU create: peak=%f", speed_.peak);
330
331   speed_integrated_trace_ = new CpuTiTmgr(nullptr, 1 /*scale*/);
332 }
333
334 CpuTi::~CpuTi()
335 {
336   set_modified(false);
337   delete speed_integrated_trace_;
338 }
339
340 void CpuTi::turn_off()
341 {
342   /* Skip CpuImpl::turn_off() that marks the actions as failing, as it seems to be done otherwise in CPU TI.
343    * So, just avoid the segfault for now.
344    *
345    * TODO: a proper solution would be to understand and adapt the way actions are marked FAILED in here,
346    * and adapt it to align with the other resources. */
347   Resource::turn_off();
348 }
349
350 CpuImpl* CpuTi::set_speed_profile(kernel::profile::Profile* profile)
351 {
352   delete speed_integrated_trace_;
353   speed_integrated_trace_ = new CpuTiTmgr(profile, speed_.scale);
354
355   /* add a fake trace event if periodicity == 0 */
356   if (profile && profile->get_event_list().size() > 1) {
357     kernel::profile::DatedValue val = profile->get_event_list().back();
358     if (val.date_ < 1e-12) {
359       auto* prof   = profile::ProfileBuilder::from_void();
360       speed_.event = prof->schedule(&profile::future_evt_set, this);
361     }
362   }
363   return this;
364 }
365
366 void CpuTi::apply_event(kernel::profile::Event* event, double value)
367 {
368   if (event == speed_.event) {
369     XBT_DEBUG("Speed changed in trace! New fixed value: %f", value);
370
371     /* update remaining of actions and put in modified cpu list */
372     update_remaining_amount(EngineImpl::get_clock());
373
374     set_modified(true);
375
376     delete speed_integrated_trace_;
377     speed_integrated_trace_ = new CpuTiTmgr(value);
378
379     speed_.scale = value;
380     tmgr_trace_event_unref(&speed_.event);
381
382   } else if (event == get_state_event()) {
383     if (value > 0) {
384       if (not is_on()) {
385         XBT_VERB("Restart actors on host %s", get_iface()->get_cname());
386         get_iface()->turn_on();
387       }
388     } else {
389       get_iface()->turn_off();
390
391       /* put all action running on cpu to failed */
392       double now = EngineImpl::get_clock();
393       for (CpuTiAction& action : action_set_) {
394         if (action.get_state() == Action::State::INITED || action.get_state() == Action::State::STARTED ||
395             action.get_state() == Action::State::IGNORED) {
396           action.set_finish_time(now);
397           action.set_state(Action::State::FAILED);
398           get_model()->get_action_heap().remove(&action);
399         }
400       }
401     }
402     unref_state_event();
403
404   } else {
405     xbt_die("Unknown event!\n");
406   }
407 }
408
409 /** Update the actions that are running on this CPU (which was modified recently) */
410 void CpuTi::update_actions_finish_time(double now)
411 {
412   /* update remaining amount of actions */
413   update_remaining_amount(now);
414
415   /* Compute the sum of priorities for the actions running on that CPU */
416   sum_priority_ = 0.0;
417   for (CpuTiAction const& action : action_set_) {
418     /* action not running, skip it */
419     if (action.get_state_set() != get_model()->get_started_action_set())
420       continue;
421
422     /* bogus priority, skip it */
423     if (action.get_sharing_penalty() <= 0)
424       continue;
425
426     /* action suspended, skip it */
427     if (not action.is_running())
428       continue;
429
430     sum_priority_ += 1.0 / action.get_sharing_penalty();
431   }
432
433   for (CpuTiAction& action : action_set_) {
434     double min_finish = NO_MAX_DURATION;
435     /* action not running, skip it */
436     if (action.get_state_set() != get_model()->get_started_action_set())
437       continue;
438
439     /* verify if the action is really running on cpu */
440     if (action.is_running() && action.get_sharing_penalty() > 0) {
441       /* total area needed to finish the action. Used in trace integration */
442       double total_area = (action.get_remains() * sum_priority_ * action.get_sharing_penalty()) / speed_.peak;
443
444       action.set_finish_time(speed_integrated_trace_->solve(now, total_area));
445       /* verify which event will happen before (max_duration or finish time) */
446       if (action.get_max_duration() != NO_MAX_DURATION &&
447           action.get_start_time() + action.get_max_duration() < action.get_finish_time())
448         min_finish = action.get_start_time() + action.get_max_duration();
449       else
450         min_finish = action.get_finish_time();
451     } else {
452       /* put the max duration time on heap */
453       if (action.get_max_duration() != NO_MAX_DURATION)
454         min_finish = action.get_start_time() + action.get_max_duration();
455     }
456     /* add in action heap */
457     if (min_finish != NO_MAX_DURATION)
458       get_model()->get_action_heap().update(&action, min_finish, ActionHeap::Type::unset);
459     else
460       get_model()->get_action_heap().remove(&action);
461
462     XBT_DEBUG("Update finish time: Cpu(%s) Action: %p, Start Time: %f Finish Time: %f Max duration %f", get_cname(),
463               &action, action.get_start_time(), action.get_finish_time(), action.get_max_duration());
464   }
465   /* remove from modified cpu */
466   set_modified(false);
467 }
468
469 bool CpuTi::is_used() const
470 {
471   return not action_set_.empty();
472 }
473
474 double CpuTi::get_speed_ratio()
475 {
476   speed_.scale = speed_integrated_trace_->get_power_scale(EngineImpl::get_clock());
477   return CpuImpl::get_speed_ratio();
478 }
479
480 /** @brief Update the remaining amount of actions */
481 void CpuTi::update_remaining_amount(double now)
482 {
483   /* already up to date */
484   if (last_update_ >= now)
485     return;
486
487   /* compute the integration area */
488   double area_total = speed_integrated_trace_->integrate(last_update_, now) * speed_.peak;
489   XBT_DEBUG("Flops total: %f, Last update %f", area_total, last_update_);
490   for (CpuTiAction& action : action_set_) {
491     /* action not running, skip it */
492     if (action.get_state_set() != get_model()->get_started_action_set())
493       continue;
494
495     /* bogus priority, skip it */
496     if (action.get_sharing_penalty() <= 0)
497       continue;
498
499     /* action suspended, skip it */
500     if (not action.is_running())
501       continue;
502
503     /* action don't need update */
504     if (action.get_start_time() >= now)
505       continue;
506
507     /* skip action that are finishing now */
508     if (action.get_finish_time() >= 0 && action.get_finish_time() <= now)
509       continue;
510
511     /* update remaining */
512     action.update_remains(area_total / (sum_priority_ * action.get_sharing_penalty()));
513     XBT_DEBUG("Update remaining action(%p) remaining %f", &action, action.get_remains_no_update());
514   }
515   last_update_ = now;
516 }
517
518 CpuAction* CpuTi::execution_start(double size, double user_bound)
519 {
520   XBT_IN("(%s,%g)", get_cname(), size);
521   xbt_assert(user_bound <= 0, "Invalid user bound (%lf) in CPU TI model", user_bound);
522   auto* action = new CpuTiAction(this, size);
523
524   action_set_.push_back(*action); // Actually start the action
525
526   XBT_OUT();
527   return action;
528 }
529
530 CpuAction* CpuTi::sleep(double duration)
531 {
532   if (duration > 0)
533     duration = std::max(duration, sg_precision_timing);
534
535   XBT_IN("(%s,%g)", get_cname(), duration);
536   auto* action = new CpuTiAction(this, 1.0);
537
538   action->set_max_duration(duration);
539   action->set_suspend_state(Action::SuspendStates::SLEEPING);
540   if (duration == NO_MAX_DURATION)
541     action->set_state(Action::State::IGNORED);
542
543   action_set_.push_back(*action);
544
545   XBT_OUT();
546   return action;
547 }
548
549 void CpuTi::set_modified(bool modified)
550 {
551   CpuTiList& modified_cpus = static_cast<CpuTiModel*>(get_model())->modified_cpus_;
552   if (modified) {
553     if (not cpu_ti_hook.is_linked()) {
554       modified_cpus.push_back(*this);
555     }
556   } else {
557     if (cpu_ti_hook.is_linked())
558       xbt::intrusive_erase(modified_cpus, *this);
559   }
560 }
561
562 /**********
563  * Action *
564  **********/
565
566 CpuTiAction::CpuTiAction(CpuTi* cpu, double cost) : CpuAction(cpu->get_model(), cost, not cpu->is_on()), cpu_(cpu)
567 {
568   cpu_->set_modified(true);
569 }
570 CpuTiAction::~CpuTiAction()
571 {
572   /* remove from action_set */
573   if (action_ti_hook.is_linked())
574     xbt::intrusive_erase(cpu_->action_set_, *this);
575   /* remove from heap */
576   get_model()->get_action_heap().remove(this);
577   cpu_->set_modified(true);
578 }
579
580 void CpuTiAction::set_state(Action::State state)
581 {
582   CpuAction::set_state(state);
583   cpu_->set_modified(true);
584 }
585
586 void CpuTiAction::cancel()
587 {
588   this->set_state(Action::State::FAILED);
589   get_model()->get_action_heap().remove(this);
590   cpu_->set_modified(true);
591 }
592
593 void CpuTiAction::suspend()
594 {
595   XBT_IN("(%p)", this);
596   if (is_running()) {
597     set_suspend_state(Action::SuspendStates::SUSPENDED);
598     get_model()->get_action_heap().remove(this);
599     cpu_->set_modified(true);
600   }
601   XBT_OUT();
602 }
603
604 void CpuTiAction::resume()
605 {
606   XBT_IN("(%p)", this);
607   if (is_suspended()) {
608     set_suspend_state(Action::SuspendStates::RUNNING);
609     cpu_->set_modified(true);
610   }
611   XBT_OUT();
612 }
613
614 void CpuTiAction::set_sharing_penalty(double sharing_penalty)
615 {
616   XBT_IN("(%p,%g)", this, sharing_penalty);
617   set_sharing_penalty_no_update(sharing_penalty);
618   cpu_->set_modified(true);
619   XBT_OUT();
620 }
621
622 double CpuTiAction::get_remains()
623 {
624   XBT_IN("(%p)", this);
625   cpu_->update_remaining_amount(EngineImpl::get_clock());
626   XBT_OUT();
627   return get_remains_no_update();
628 }
629
630 } // namespace simgrid::kernel::resource