Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
NO_MAX_DURATION is a double.
[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 "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/surf/surf_interface.hpp"
13 #include "surf/surf.hpp"
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 {
23 namespace kernel {
24 namespace resource {
25
26 /*********
27  * Trace *
28  *********/
29
30 CpuTiProfile::CpuTiProfile(const profile::Profile* profile)
31 {
32   double integral    = 0;
33   double time        = 0;
34   unsigned nb_points = profile->get_event_list().size() + 1;
35   time_points_.reserve(nb_points);
36   integral_.reserve(nb_points);
37   for (auto const& val : profile->get_event_list()) {
38     time_points_.push_back(time);
39     integral_.push_back(integral);
40     time += val.date_;
41     integral += val.date_ * val.value_;
42   }
43   time_points_.push_back(time);
44   integral_.push_back(integral);
45 }
46
47 /**
48  * @brief Integrate trace
49  *
50  * Wrapper around surf_cpu_integrate_trace_simple() to get
51  * the cyclic effect.
52  *
53  * @param a      Begin of interval
54  * @param b      End of interval
55  * @return the integrate value. -1 if an error occurs.
56  */
57 double CpuTiTmgr::integrate(double a, double b) const
58 {
59   xbt_assert(a >= 0.0 && a <= b,
60              "Error, invalid integration interval [%.2f,%.2f]. You probably have a task executing with negative "
61              "computation amount. Check your code.",
62              a, b);
63   if (fabs(a - b) < EPSILON)
64     return 0.0;
65
66   if (type_ == Type::FIXED) {
67     return (b - a) * value_;
68   }
69
70   double a_index;
71   if (fabs(ceil(a / last_time_) - a / last_time_) < EPSILON)
72     a_index = 1 + ceil(a / last_time_);
73   else
74     a_index = ceil(a / last_time_);
75   double b_index = floor(b / last_time_);
76
77   if (a_index > b_index) { /* Same chunk */
78     return profile_->integrate_simple(a - (a_index - 1) * last_time_, b - b_index * last_time_);
79   }
80
81   double first_chunk  = profile_->integrate_simple(a - (a_index - 1) * last_time_, last_time_);
82   double middle_chunk = (b_index - a_index) * total_;
83   double last_chunk   = profile_->integrate_simple(0.0, b - b_index * last_time_);
84
85   XBT_DEBUG("first_chunk=%.2f  middle_chunk=%.2f  last_chunk=%.2f\n", first_chunk, middle_chunk, last_chunk);
86
87   return (first_chunk + middle_chunk + last_chunk);
88 }
89
90 /**
91  * @brief Auxiliary function to compute the integral between a and b.
92  *     It simply computes the integrals at point a and b and returns the difference between them.
93  * @param a  Initial point
94  * @param b  Final point
95  */
96 double CpuTiProfile::integrate_simple(double a, double b) const
97 {
98   return integrate_simple_point(b) - integrate_simple_point(a);
99 }
100
101 /**
102  * @brief Auxiliary function to compute the integral at point a.
103  * @param a        point
104  */
105 double CpuTiProfile::integrate_simple_point(double a) const
106 {
107   double integral = 0;
108   double a_aux    = a;
109   int ind         = binary_search(time_points_, a);
110   integral += integral_[ind];
111
112   XBT_DEBUG("a %f ind %d integral %f ind + 1 %f ind %f time +1 %f time %f", a, ind, integral, integral_[ind + 1],
113             integral_[ind], time_points_[ind + 1], time_points_[ind]);
114   double_update(&a_aux, time_points_[ind], sg_maxmin_precision * sg_surf_precision);
115   if (a_aux > 0)
116     integral +=
117         ((integral_[ind + 1] - integral_[ind]) / (time_points_[ind + 1] - time_points_[ind])) * (a - time_points_[ind]);
118   XBT_DEBUG("Integral a %f = %f", a, integral);
119
120   return integral;
121 }
122
123 /**
124  * @brief Computes the time needed to execute "amount" on cpu.
125  *
126  * Here, amount can span multiple trace periods
127  *
128  * @param a        Initial time
129  * @param amount  Amount to be executed
130  * @return  End time
131  */
132 double CpuTiTmgr::solve(double a, double amount) const
133 {
134   /* Fix very small negative numbers */
135   if ((a < 0.0) && (a > -EPSILON)) {
136     a = 0.0;
137   }
138   if ((amount < 0.0) && (amount > -EPSILON)) {
139     amount = 0.0;
140   }
141
142   /* Sanity checks */
143   xbt_assert(a >= 0.0 && amount >= 0.0,
144              "Error, invalid parameters [a = %.2f, amount = %.2f]. "
145              "You probably have a task executing with negative computation amount. Check your code.",
146              a, amount);
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_->get_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->get_event_list().size() == 1) {
234     value_ = speed_profile->get_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->get_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_models()
271 {
272   auto cpu_model_pm = std::make_shared<CpuTiModel>("Cpu_TI");
273   simgrid::kernel::EngineImpl::get_instance()->add_model(cpu_model_pm);
274   simgrid::s4u::Engine::get_instance()->get_netzone_root()->get_impl()->set_cpu_pm_model(cpu_model_pm);
275 }
276
277 Cpu* CpuTiModel::create_cpu(s4u::Host* host, const std::vector<double>& speed_per_pstate)
278 {
279   return (new CpuTi(host, speed_per_pstate))->set_model(this);
280 }
281
282 double CpuTiModel::next_occurring_event(double now)
283 {
284   double min_action_duration = -1;
285
286   /* iterates over modified cpus to update share resources */
287   for (auto it = std::begin(modified_cpus_); it != std::end(modified_cpus_);) {
288     CpuTi& cpu = *it;
289     ++it; // increment iterator here since the following call to ti.update_actions_finish_time() may invalidate it
290     cpu.update_actions_finish_time(now);
291   }
292
293   /* get the min next event if heap not empty */
294   if (not get_action_heap().empty())
295     min_action_duration = get_action_heap().top_date() - now;
296
297   XBT_DEBUG("Share resources, min next event date: %f", min_action_duration);
298
299   return min_action_duration;
300 }
301
302 void CpuTiModel::update_actions_state(double now, double /*delta*/)
303 {
304   while (not get_action_heap().empty() && double_equals(get_action_heap().top_date(), now, sg_surf_precision)) {
305     auto* action = static_cast<CpuTiAction*>(get_action_heap().pop());
306     XBT_DEBUG("Action %p: finish", action);
307     action->finish(Action::State::FINISHED);
308     /* update remaining amount of all actions */
309     action->cpu_->update_remaining_amount(surf_get_clock());
310   }
311 }
312
313 /************
314  * Resource *
315  ************/
316 CpuTi::CpuTi(s4u::Host* host, const std::vector<double>& speed_per_pstate) : Cpu(host, speed_per_pstate)
317 {
318   speed_.peak = speed_per_pstate.front();
319   XBT_DEBUG("CPU create: peak=%f", speed_.peak);
320
321   speed_integrated_trace_ = new CpuTiTmgr(nullptr, 1 /*scale*/);
322 }
323
324 CpuTi::~CpuTi()
325 {
326   set_modified(false);
327   delete speed_integrated_trace_;
328 }
329
330 Cpu* CpuTi::set_speed_profile(kernel::profile::Profile* profile)
331 {
332   delete speed_integrated_trace_;
333   speed_integrated_trace_ = new CpuTiTmgr(profile, speed_.scale);
334
335   /* add a fake trace event if periodicity == 0 */
336   if (profile && profile->get_event_list().size() > 1) {
337     kernel::profile::DatedValue val = profile->get_event_list().back();
338     if (val.date_ < 1e-12) {
339       auto* prof   = new kernel::profile::Profile();
340       speed_.event = prof->schedule(&profile::future_evt_set, this);
341     }
342   }
343   return this;
344 }
345
346 void CpuTi::apply_event(kernel::profile::Event* event, double value)
347 {
348   if (event == speed_.event) {
349     XBT_DEBUG("Speed changed in trace! New fixed value: %f", value);
350
351     /* update remaining of actions and put in modified cpu list */
352     update_remaining_amount(surf_get_clock());
353
354     set_modified(true);
355
356     delete speed_integrated_trace_;
357     speed_integrated_trace_ = new CpuTiTmgr(value);
358
359     speed_.scale = value;
360     tmgr_trace_event_unref(&speed_.event);
361
362   } else if (event == state_event_) {
363     if (value > 0) {
364       if (not is_on()) {
365         XBT_VERB("Restart actors on host %s", get_iface()->get_cname());
366         get_iface()->turn_on();
367       }
368     } else {
369       get_iface()->turn_off();
370       double date = surf_get_clock();
371
372       /* put all action running on cpu to failed */
373       for (CpuTiAction& action : action_set_) {
374         if (action.get_state() == Action::State::INITED || action.get_state() == Action::State::STARTED ||
375             action.get_state() == Action::State::IGNORED) {
376           action.set_finish_time(date);
377           action.set_state(Action::State::FAILED);
378           get_model()->get_action_heap().remove(&action);
379         }
380       }
381     }
382     tmgr_trace_event_unref(&state_event_);
383
384   } else {
385     xbt_die("Unknown event!\n");
386   }
387 }
388
389 /** Update the actions that are running on this CPU (which was modified recently) */
390 void CpuTi::update_actions_finish_time(double now)
391 {
392   /* update remaining amount of actions */
393   update_remaining_amount(now);
394
395   /* Compute the sum of priorities for the actions running on that CPU */
396   sum_priority_ = 0.0;
397   for (CpuTiAction const& action : action_set_) {
398     /* action not running, skip it */
399     if (action.get_state_set() != get_model()->get_started_action_set())
400       continue;
401
402     /* bogus priority, skip it */
403     if (action.get_sharing_penalty() <= 0)
404       continue;
405
406     /* action suspended, skip it */
407     if (not action.is_running())
408       continue;
409
410     sum_priority_ += 1.0 / action.get_sharing_penalty();
411   }
412
413   for (CpuTiAction& action : action_set_) {
414     double min_finish = NO_MAX_DURATION;
415     /* action not running, skip it */
416     if (action.get_state_set() != get_model()->get_started_action_set())
417       continue;
418
419     /* verify if the action is really running on cpu */
420     if (action.is_running() && action.get_sharing_penalty() > 0) {
421       /* total area needed to finish the action. Used in trace integration */
422       double total_area = (action.get_remains() * sum_priority_ * action.get_sharing_penalty()) / speed_.peak;
423
424       action.set_finish_time(speed_integrated_trace_->solve(now, total_area));
425       /* verify which event will happen before (max_duration or finish time) */
426       if (action.get_max_duration() != NO_MAX_DURATION &&
427           action.get_start_time() + action.get_max_duration() < action.get_finish_time())
428         min_finish = action.get_start_time() + action.get_max_duration();
429       else
430         min_finish = action.get_finish_time();
431     } else {
432       /* put the max duration time on heap */
433       if (action.get_max_duration() != NO_MAX_DURATION)
434         min_finish = action.get_start_time() + action.get_max_duration();
435     }
436     /* add in action heap */
437     if (min_finish != NO_MAX_DURATION)
438       get_model()->get_action_heap().update(&action, min_finish, ActionHeap::Type::unset);
439     else
440       get_model()->get_action_heap().remove(&action);
441
442     XBT_DEBUG("Update finish time: Cpu(%s) Action: %p, Start Time: %f Finish Time: %f Max duration %f", get_cname(),
443               &action, action.get_start_time(), action.get_finish_time(), action.get_max_duration());
444   }
445   /* remove from modified cpu */
446   set_modified(false);
447 }
448
449 bool CpuTi::is_used() const
450 {
451   return not action_set_.empty();
452 }
453
454 double CpuTi::get_speed_ratio()
455 {
456   speed_.scale = speed_integrated_trace_->get_power_scale(surf_get_clock());
457   return Cpu::get_speed_ratio();
458 }
459
460 /** @brief Update the remaining amount of actions */
461 void CpuTi::update_remaining_amount(double now)
462 {
463   /* already up to date */
464   if (last_update_ >= now)
465     return;
466
467   /* compute the integration area */
468   double area_total = speed_integrated_trace_->integrate(last_update_, now) * speed_.peak;
469   XBT_DEBUG("Flops total: %f, Last update %f", area_total, last_update_);
470   for (CpuTiAction& action : action_set_) {
471     /* action not running, skip it */
472     if (action.get_state_set() != get_model()->get_started_action_set())
473       continue;
474
475     /* bogus priority, skip it */
476     if (action.get_sharing_penalty() <= 0)
477       continue;
478
479     /* action suspended, skip it */
480     if (not action.is_running())
481       continue;
482
483     /* action don't need update */
484     if (action.get_start_time() >= now)
485       continue;
486
487     /* skip action that are finishing now */
488     if (action.get_finish_time() >= 0 && action.get_finish_time() <= now)
489       continue;
490
491     /* update remaining */
492     action.update_remains(area_total / (sum_priority_ * action.get_sharing_penalty()));
493     XBT_DEBUG("Update remaining action(%p) remaining %f", &action, action.get_remains_no_update());
494   }
495   last_update_ = now;
496 }
497
498 CpuAction* CpuTi::execution_start(double size)
499 {
500   XBT_IN("(%s,%g)", get_cname(), size);
501   auto* action = new CpuTiAction(this, size);
502
503   action_set_.push_back(*action); // Actually start the action
504
505   XBT_OUT();
506   return action;
507 }
508
509 CpuAction* CpuTi::sleep(double duration)
510 {
511   if (duration > 0)
512     duration = std::max(duration, sg_surf_precision);
513
514   XBT_IN("(%s,%g)", get_cname(), duration);
515   auto* action = new CpuTiAction(this, 1.0);
516
517   action->set_max_duration(duration);
518   action->set_suspend_state(Action::SuspendStates::SLEEPING);
519   if (duration == NO_MAX_DURATION)
520     action->set_state(Action::State::IGNORED);
521
522   action_set_.push_back(*action);
523
524   XBT_OUT();
525   return action;
526 }
527
528 void CpuTi::set_modified(bool modified)
529 {
530   CpuTiList& modified_cpus = static_cast<CpuTiModel*>(get_model())->modified_cpus_;
531   if (modified) {
532     if (not cpu_ti_hook.is_linked()) {
533       modified_cpus.push_back(*this);
534     }
535   } else {
536     if (cpu_ti_hook.is_linked())
537       xbt::intrusive_erase(modified_cpus, *this);
538   }
539 }
540
541 /**********
542  * Action *
543  **********/
544
545 CpuTiAction::CpuTiAction(CpuTi* cpu, double cost) : CpuAction(cpu->get_model(), cost, not cpu->is_on()), cpu_(cpu)
546 {
547   cpu_->set_modified(true);
548 }
549 CpuTiAction::~CpuTiAction()
550 {
551   /* remove from action_set */
552   if (action_ti_hook.is_linked())
553     xbt::intrusive_erase(cpu_->action_set_, *this);
554   /* remove from heap */
555   get_model()->get_action_heap().remove(this);
556   cpu_->set_modified(true);
557 }
558
559 void CpuTiAction::set_state(Action::State state)
560 {
561   CpuAction::set_state(state);
562   cpu_->set_modified(true);
563 }
564
565 void CpuTiAction::cancel()
566 {
567   this->set_state(Action::State::FAILED);
568   get_model()->get_action_heap().remove(this);
569   cpu_->set_modified(true);
570 }
571
572 void CpuTiAction::suspend()
573 {
574   XBT_IN("(%p)", this);
575   if (is_running()) {
576     set_suspend_state(Action::SuspendStates::SUSPENDED);
577     get_model()->get_action_heap().remove(this);
578     cpu_->set_modified(true);
579   }
580   XBT_OUT();
581 }
582
583 void CpuTiAction::resume()
584 {
585   XBT_IN("(%p)", this);
586   if (is_suspended()) {
587     set_suspend_state(Action::SuspendStates::RUNNING);
588     cpu_->set_modified(true);
589   }
590   XBT_OUT();
591 }
592
593 void CpuTiAction::set_max_duration(double duration)
594 {
595   double min_finish;
596
597   XBT_IN("(%p,%g)", this, duration);
598
599   Action::set_max_duration(duration);
600
601   if (duration >= 0)
602     min_finish = (get_start_time() + get_max_duration()) < get_finish_time() ? (get_start_time() + get_max_duration())
603                                                                              : get_finish_time();
604   else
605     min_finish = get_finish_time();
606
607   /* add in action heap */
608   get_model()->get_action_heap().update(this, min_finish, ActionHeap::Type::unset);
609
610   XBT_OUT();
611 }
612
613 void CpuTiAction::set_sharing_penalty(double sharing_penalty)
614 {
615   XBT_IN("(%p,%g)", this, sharing_penalty);
616   set_sharing_penalty_no_update(sharing_penalty);
617   cpu_->set_modified(true);
618   XBT_OUT();
619 }
620
621 double CpuTiAction::get_remains()
622 {
623   XBT_IN("(%p)", this);
624   cpu_->update_remaining_amount(surf_get_clock());
625   XBT_OUT();
626   return get_remains_no_update();
627 }
628
629 } // namespace resource
630 } // namespace kernel
631 } // namespace simgrid