Logo AND Algorithmique Numérique Distribuée

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