Logo AND Algorithmique Numérique Distribuée

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