Logo AND Algorithmique Numérique Distribuée

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