Logo AND Algorithmique Numérique Distribuée

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