1 /* Copyright (c) 2013-2022. The SimGrid Team. All rights reserved. */
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. */
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"
18 constexpr double EPSILON = 0.000000001;
20 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(cpu_ti, res_cpu, "CPU resource, Trace Integration model");
22 namespace simgrid::kernel::resource {
28 CpuTiProfile::CpuTiProfile(const profile::Profile* profile)
32 double prev_value = 1;
33 const std::vector<profile::DatedValue>& events=profile->get_event_list();
34 xbt_assert(not events.empty());
35 unsigned long nb_points = events.size() + 1;
36 time_points_.reserve(nb_points);
37 integral_.reserve(nb_points);
38 for (auto const& val : events) {
40 integral += val.date_ * prev_value;
41 time_points_.push_back(time);
42 integral_.push_back(integral);
43 prev_value = val.value_;
46 double delay=profile->get_repeat_delay()+ events.at(0).date_;
48 xbt_assert( events.back().value_==prev_value,"Profiles need to end as they start");
50 integral += delay*prev_value;
52 time_points_.push_back(time);
53 integral_.push_back(integral);
57 * @brief Integrate trace
59 * Wrapper around surf_cpu_integrate_trace_simple() to get
62 * @param a Begin of interval
63 * @param b End of interval
64 * @return the integrate value. -1 if an error occurs.
66 double CpuTiTmgr::integrate(double a, double b) const
68 xbt_assert(a >= 0.0 && a <= b,
69 "Error, invalid integration interval [%.2f,%.2f]. You probably have a task executing with negative "
70 "computation amount. Check your code.",
72 if (fabs(a - b) < EPSILON)
75 if (type_ == Type::FIXED) {
76 return (b - a) * value_;
80 if (fabs(ceil(a / last_time_) - a / last_time_) < EPSILON)
81 a_index = 1 + ceil(a / last_time_);
83 a_index = ceil(a / last_time_);
84 double b_index = floor(b / last_time_);
86 if (a_index > b_index) { /* Same chunk */
87 return profile_->integrate_simple(a - (a_index - 1) * last_time_, b - b_index * last_time_);
90 double first_chunk = profile_->integrate_simple(a - (a_index - 1) * last_time_, last_time_);
91 double middle_chunk = (b_index - a_index) * total_;
92 double last_chunk = profile_->integrate_simple(0.0, b - b_index * last_time_);
94 XBT_DEBUG("first_chunk=%.2f middle_chunk=%.2f last_chunk=%.2f\n", first_chunk, middle_chunk, last_chunk);
96 return (first_chunk + middle_chunk + last_chunk);
100 * @brief Auxiliary function to compute the integral between a and b.
101 * It simply computes the integrals at point a and b and returns the difference between them.
102 * @param a Initial point
103 * @param b Final point
105 double CpuTiProfile::integrate_simple(double a, double b) const
107 return integrate_simple_point(b) - integrate_simple_point(a);
111 * @brief Auxiliary function to compute the integral at point a.
114 double CpuTiProfile::integrate_simple_point(double a) const
118 long ind = binary_search(time_points_, a);
119 integral += integral_[ind];
121 XBT_DEBUG("a %f ind %ld integral %f ind + 1 %f ind %f time +1 %f time %f", a, ind, integral, integral_[ind + 1],
122 integral_[ind], time_points_[ind + 1], time_points_[ind]);
123 double_update(&a_aux, time_points_[ind], sg_maxmin_precision * sg_surf_precision);
126 ((integral_[ind + 1] - integral_[ind]) / (time_points_[ind + 1] - time_points_[ind])) * (a - time_points_[ind]);
127 XBT_DEBUG("Integral a %f = %f", a, integral);
133 * @brief Computes the time needed to execute "amount" on cpu.
135 * Here, amount can span multiple trace periods
137 * @param a Initial time
138 * @param amount Amount to be executed
141 double CpuTiTmgr::solve(double a, double amount) const
143 /* Fix very small negative numbers */
144 if ((a < 0.0) && (a > -EPSILON)) {
147 if ((amount < 0.0) && (amount > -EPSILON)) {
152 xbt_assert(a >= 0.0 && amount >= 0.0,
153 "Error, invalid parameters [a = %.2f, amount = %.2f]. "
154 "You probably have a task executing with negative computation amount. Check your code.",
157 /* At this point, a and amount are positive */
158 if (amount < EPSILON)
161 /* Is the trace fixed ? */
162 if (type_ == Type::FIXED) {
163 return (a + (amount / value_));
166 XBT_DEBUG("amount %f total %f", amount, total_);
167 /* Reduce the problem to one where amount <= trace_total */
168 double quotient = floor(amount / total_);
169 double reduced_amount = total_ * ((amount / total_) - floor(amount / total_));
170 double reduced_a = a - last_time_ * static_cast<int>(floor(a / last_time_));
172 XBT_DEBUG("Quotient: %g reduced_amount: %f reduced_a: %f", quotient, reduced_amount, reduced_a);
174 /* Now solve for new_amount which is <= trace_total */
175 XBT_DEBUG("Solve integral: [%.2f, amount=%.2f]", reduced_a, reduced_amount);
177 double amount_till_end = integrate(reduced_a, last_time_);
178 double reduced_b = amount_till_end > reduced_amount
179 ? profile_->solve_simple(reduced_a, reduced_amount)
180 : last_time_ + profile_->solve_simple(0.0, reduced_amount - amount_till_end);
182 /* Re-map to the original b and amount */
183 return last_time_ * floor(a / last_time_) + (quotient * last_time_) + reduced_b;
187 * @brief Auxiliary function to solve integral.
188 * It returns the date when the requested amount of flops is available
189 * @param a Initial point
190 * @param amount Amount of flops
191 * @return The date when amount is available.
193 double CpuTiProfile::solve_simple(double a, double amount) const
195 double integral_a = integrate_simple_point(a);
196 long ind = binary_search(integral_, integral_a + amount);
197 double time = time_points_[ind];
198 time += (integral_a + amount - integral_[ind]) /
199 ((integral_[ind + 1] - integral_[ind]) / (time_points_[ind + 1] - time_points_[ind]));
205 * @brief Auxiliary function to update the CPU speed scale.
207 * This function uses the trace structure to return the speed scale at the determined time a.
209 * @return CPU speed scale
211 double CpuTiTmgr::get_power_scale(double a) const
213 double reduced_a = a - floor(a / last_time_) * last_time_;
214 long point = CpuTiProfile::binary_search(profile_->get_time_points(), reduced_a);
215 profile::DatedValue val = speed_profile_->get_event_list().at(point);
220 * @brief Creates a new integration trace from a tmgr_trace_t
222 * @param speed_trace CPU availability trace
223 * @param value Percentage of CPU speed available (useful to fixed tracing)
224 * @return Integration trace structure
226 CpuTiTmgr::CpuTiTmgr(kernel::profile::Profile* speed_profile, double value) : speed_profile_(speed_profile)
228 double total_time = 0.0;
229 profile_.reset(nullptr);
231 /* no availability file, fixed trace */
232 if (not speed_profile) {
234 XBT_DEBUG("No availability trace. Constant value = %f", value);
238 xbt_assert(speed_profile->is_repeating());
240 /* only one point available, fixed trace */
241 if (speed_profile->get_event_list().size() == 1) {
242 value_ = speed_profile->get_event_list().front().value_;
246 type_ = Type::DYNAMIC;
248 /* count the total time of trace file */
249 for (auto const& val : speed_profile->get_event_list())
250 total_time += val.date_;
251 total_time += speed_profile->get_repeat_delay();
253 profile_ = std::make_unique<CpuTiProfile>(speed_profile);
254 last_time_ = total_time;
255 total_ = profile_->integrate_simple(0, total_time);
257 XBT_DEBUG("Total integral %f, last_time %f ", total_, last_time_);
261 * @brief Binary search in array.
262 * It returns the last point of the interval in which "a" is.
264 * @param a Value to search
265 * @return Index of point
267 long CpuTiProfile::binary_search(const std::vector<double>& array, double a)
271 auto pos = std::upper_bound(begin(array), end(array), a);
272 return std::distance(begin(array), pos) - 1;
279 void CpuTiModel::create_pm_models()
281 auto cpu_model_pm = std::make_shared<CpuTiModel>("Cpu_TI");
282 auto* engine = EngineImpl::get_instance();
283 engine->add_model(cpu_model_pm);
284 engine->get_netzone_root()->set_cpu_pm_model(cpu_model_pm);
287 CpuImpl* CpuTiModel::create_cpu(s4u::Host* host, const std::vector<double>& speed_per_pstate)
289 return (new CpuTi(host, speed_per_pstate))->set_model(this);
292 double CpuTiModel::next_occurring_event(double now)
294 double min_action_duration = -1;
296 /* iterates over modified cpus to update share resources */
297 for (auto it = std::begin(modified_cpus_); it != std::end(modified_cpus_);) {
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);
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;
307 XBT_DEBUG("Share resources, min next event date: %f", min_action_duration);
309 return min_action_duration;
312 void CpuTiModel::update_actions_state(double now, double /*delta*/)
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(EngineImpl::get_clock());
326 CpuTi::CpuTi(s4u::Host* host, const std::vector<double>& speed_per_pstate) : CpuImpl(host, speed_per_pstate)
328 speed_.peak = speed_per_pstate.front();
329 XBT_DEBUG("CPU create: peak=%f", speed_.peak);
331 speed_integrated_trace_ = new CpuTiTmgr(nullptr, 1 /*scale*/);
337 delete speed_integrated_trace_;
340 CpuImpl* CpuTi::set_speed_profile(kernel::profile::Profile* profile)
342 delete speed_integrated_trace_;
343 speed_integrated_trace_ = new CpuTiTmgr(profile, speed_.scale);
345 /* add a fake trace event if periodicity == 0 */
346 if (profile && profile->get_event_list().size() > 1) {
347 kernel::profile::DatedValue val = profile->get_event_list().back();
348 if (val.date_ < 1e-12) {
349 auto* prof = profile::ProfileBuilder::from_void();
350 speed_.event = prof->schedule(&profile::future_evt_set, this);
356 void CpuTi::apply_event(kernel::profile::Event* event, double value)
358 if (event == speed_.event) {
359 XBT_DEBUG("Speed changed in trace! New fixed value: %f", value);
361 /* update remaining of actions and put in modified cpu list */
362 update_remaining_amount(EngineImpl::get_clock());
366 delete speed_integrated_trace_;
367 speed_integrated_trace_ = new CpuTiTmgr(value);
369 speed_.scale = value;
370 tmgr_trace_event_unref(&speed_.event);
372 } else if (event == get_state_event()) {
375 XBT_VERB("Restart actors on host %s", get_iface()->get_cname());
376 get_iface()->turn_on();
379 get_iface()->turn_off();
380 double date = EngineImpl::get_clock();
382 /* put all action running on cpu to failed */
383 for (CpuTiAction& action : action_set_) {
384 if (action.get_state() == Action::State::INITED || action.get_state() == Action::State::STARTED ||
385 action.get_state() == Action::State::IGNORED) {
386 action.set_finish_time(date);
387 action.set_state(Action::State::FAILED);
388 get_model()->get_action_heap().remove(&action);
395 xbt_die("Unknown event!\n");
399 /** Update the actions that are running on this CPU (which was modified recently) */
400 void CpuTi::update_actions_finish_time(double now)
402 /* update remaining amount of actions */
403 update_remaining_amount(now);
405 /* Compute the sum of priorities for the actions running on that CPU */
407 for (CpuTiAction const& action : action_set_) {
408 /* action not running, skip it */
409 if (action.get_state_set() != get_model()->get_started_action_set())
412 /* bogus priority, skip it */
413 if (action.get_sharing_penalty() <= 0)
416 /* action suspended, skip it */
417 if (not action.is_running())
420 sum_priority_ += 1.0 / action.get_sharing_penalty();
423 for (CpuTiAction& action : action_set_) {
424 double min_finish = NO_MAX_DURATION;
425 /* action not running, skip it */
426 if (action.get_state_set() != get_model()->get_started_action_set())
429 /* verify if the action is really running on cpu */
430 if (action.is_running() && action.get_sharing_penalty() > 0) {
431 /* total area needed to finish the action. Used in trace integration */
432 double total_area = (action.get_remains() * sum_priority_ * action.get_sharing_penalty()) / speed_.peak;
434 action.set_finish_time(speed_integrated_trace_->solve(now, total_area));
435 /* verify which event will happen before (max_duration or finish time) */
436 if (action.get_max_duration() != NO_MAX_DURATION &&
437 action.get_start_time() + action.get_max_duration() < action.get_finish_time())
438 min_finish = action.get_start_time() + action.get_max_duration();
440 min_finish = action.get_finish_time();
442 /* put the max duration time on heap */
443 if (action.get_max_duration() != NO_MAX_DURATION)
444 min_finish = action.get_start_time() + action.get_max_duration();
446 /* add in action heap */
447 if (min_finish != NO_MAX_DURATION)
448 get_model()->get_action_heap().update(&action, min_finish, ActionHeap::Type::unset);
450 get_model()->get_action_heap().remove(&action);
452 XBT_DEBUG("Update finish time: Cpu(%s) Action: %p, Start Time: %f Finish Time: %f Max duration %f", get_cname(),
453 &action, action.get_start_time(), action.get_finish_time(), action.get_max_duration());
455 /* remove from modified cpu */
459 bool CpuTi::is_used() const
461 return not action_set_.empty();
464 double CpuTi::get_speed_ratio()
466 speed_.scale = speed_integrated_trace_->get_power_scale(EngineImpl::get_clock());
467 return CpuImpl::get_speed_ratio();
470 /** @brief Update the remaining amount of actions */
471 void CpuTi::update_remaining_amount(double now)
473 /* already up to date */
474 if (last_update_ >= now)
477 /* compute the integration area */
478 double area_total = speed_integrated_trace_->integrate(last_update_, now) * speed_.peak;
479 XBT_DEBUG("Flops total: %f, Last update %f", area_total, last_update_);
480 for (CpuTiAction& action : action_set_) {
481 /* action not running, skip it */
482 if (action.get_state_set() != get_model()->get_started_action_set())
485 /* bogus priority, skip it */
486 if (action.get_sharing_penalty() <= 0)
489 /* action suspended, skip it */
490 if (not action.is_running())
493 /* action don't need update */
494 if (action.get_start_time() >= now)
497 /* skip action that are finishing now */
498 if (action.get_finish_time() >= 0 && action.get_finish_time() <= now)
501 /* update remaining */
502 action.update_remains(area_total / (sum_priority_ * action.get_sharing_penalty()));
503 XBT_DEBUG("Update remaining action(%p) remaining %f", &action, action.get_remains_no_update());
508 CpuAction* CpuTi::execution_start(double size, double user_bound)
510 XBT_IN("(%s,%g)", get_cname(), size);
511 xbt_assert(user_bound <= 0, "Invalid user bound (%lf) in CPU TI model", user_bound);
512 auto* action = new CpuTiAction(this, size);
514 action_set_.push_back(*action); // Actually start the action
520 CpuAction* CpuTi::sleep(double duration)
523 duration = std::max(duration, sg_surf_precision);
525 XBT_IN("(%s,%g)", get_cname(), duration);
526 auto* action = new CpuTiAction(this, 1.0);
528 action->set_max_duration(duration);
529 action->set_suspend_state(Action::SuspendStates::SLEEPING);
530 if (duration == NO_MAX_DURATION)
531 action->set_state(Action::State::IGNORED);
533 action_set_.push_back(*action);
539 void CpuTi::set_modified(bool modified)
541 CpuTiList& modified_cpus = static_cast<CpuTiModel*>(get_model())->modified_cpus_;
543 if (not cpu_ti_hook.is_linked()) {
544 modified_cpus.push_back(*this);
547 if (cpu_ti_hook.is_linked())
548 xbt::intrusive_erase(modified_cpus, *this);
556 CpuTiAction::CpuTiAction(CpuTi* cpu, double cost) : CpuAction(cpu->get_model(), cost, not cpu->is_on()), cpu_(cpu)
558 cpu_->set_modified(true);
560 CpuTiAction::~CpuTiAction()
562 /* remove from action_set */
563 if (action_ti_hook.is_linked())
564 xbt::intrusive_erase(cpu_->action_set_, *this);
565 /* remove from heap */
566 get_model()->get_action_heap().remove(this);
567 cpu_->set_modified(true);
570 void CpuTiAction::set_state(Action::State state)
572 CpuAction::set_state(state);
573 cpu_->set_modified(true);
576 void CpuTiAction::cancel()
578 this->set_state(Action::State::FAILED);
579 get_model()->get_action_heap().remove(this);
580 cpu_->set_modified(true);
583 void CpuTiAction::suspend()
585 XBT_IN("(%p)", this);
587 set_suspend_state(Action::SuspendStates::SUSPENDED);
588 get_model()->get_action_heap().remove(this);
589 cpu_->set_modified(true);
594 void CpuTiAction::resume()
596 XBT_IN("(%p)", this);
597 if (is_suspended()) {
598 set_suspend_state(Action::SuspendStates::RUNNING);
599 cpu_->set_modified(true);
604 void CpuTiAction::set_sharing_penalty(double sharing_penalty)
606 XBT_IN("(%p,%g)", this, sharing_penalty);
607 set_sharing_penalty_no_update(sharing_penalty);
608 cpu_->set_modified(true);
612 double CpuTiAction::get_remains()
614 XBT_IN("(%p)", this);
615 cpu_->update_remaining_amount(EngineImpl::get_clock());
617 return get_remains_no_update();
620 } // namespace simgrid::kernel::resource