]> AND Private Git Repository - loba.git/blob - process.cpp
Logo AND Algorithmique Numérique Distribuée

Private GIT Repository
Remove usage of std::bind.
[loba.git] / process.cpp
1 #include <algorithm>
2 #include <cmath>
3 #include <iterator>
4 #include <numeric>
5 #include <stdexcept>
6 #include <sstream>
7 #include <xbt/log.h>
8
9 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(proc);
10
11 #include "misc.h"
12 #include "options.h"
13 #include "tracing.h"
14
15 #include "process.h"
16
17 mutex_t *process::proc_mutex;
18
19 double process::total_load_init = 0.0;
20 double process::total_load_running = 0.0;
21 double process::total_load_exit = 0.0;
22
23 int process::process_counter = 0;
24 double process::total_load_average;
25 double process::average_load_ratio;
26 double process::load_diff_threshold;
27
28 std::atomic<int> process::convergence_counter(0);
29
30 namespace {
31
32     void sleep_until_date(double& date, double duration)
33     {
34         double sleep_duration = date - MSG_get_clock();
35         if (sleep_duration > 0.0)
36             MSG_process_sleep(sleep_duration);
37         date = MSG_get_clock() + duration;
38     }
39
40 }
41
42 process::process(int argc, char* argv[])
43 {
44     if (argc < 2 || !(std::istringstream(argv[1]) >> real_load))
45         throw std::invalid_argument("bad or missing initial load parameter");
46
47     double iload = std::trunc(real_load);
48     if (opt::integer_transfer && real_load != iload) {
49         XBT_WARN("Initial load %g is not an integer.  Truncate it.",
50                  real_load);
51         real_load = iload;
52     }
53
54     neigh.assign(argv + 2, argv + argc);
55
56     pneigh.reserve(neigh.size());
57     for (unsigned i = 0 ; i < neigh.size() ; i++) {
58         neighbor* ptr = &neigh[i];
59         msg_host_t host = MSG_get_host_by_name(ptr->get_name());
60         pneigh.push_back(ptr);
61         rev_neigh.insert(std::make_pair(host, ptr));
62     }
63
64     prev_load_broadcast = -1;   // force sending of load on first send_all()
65     expected_load = real_load;
66     received_load = 0.0;
67
68     idle_duration = 0.0;
69     convergence = -1.0;
70
71     proc_mutex->acquire();
72     process_counter++;
73     convergence_counter++;
74     total_load_init += real_load;
75     total_load_running += real_load;
76     total_load_average = total_load_running / process_counter;
77     if (opt::avg_load_ratio >= 0.0)
78         average_load_ratio = opt::avg_load_ratio;
79     else
80         average_load_ratio = 100.0 *
81             (process_counter / -opt::avg_load_ratio) / total_load_average;
82     load_diff_threshold = (opt::load_ratio_threshold +
83                            average_load_ratio * total_load_average) / 100.0;
84     proc_mutex->release();
85
86     ctrl_close_pending = data_close_pending = neigh.size();
87     close_received = false;
88     finalizing = false;
89
90     all_comp_iter = comp_iter = lb_iter = 0;
91
92     lb_thread = new_msg_thread("loba", [this]() { this->load_balance_loop(); });
93
94     e_xbt_log_priority_t logp = xbt_log_priority_verbose;
95     if (!LOG_ISENABLED(logp))
96         return;
97     std::ostringstream oss;
98     oss << neigh.size() << " neighbor";
99     if (!neigh.empty()) {
100         oss << ESSE(neigh.size()) << ": ";
101         std::transform(neigh.begin(), neigh.end() - 1,
102                        std::ostream_iterator<const char*>(oss, ", "),
103                        [](const neighbor& neigh) { return neigh.get_name(); });
104         oss << neigh.back().get_name();
105     }
106     XBT_LOG(logp, "Got %s.", oss.str().c_str());
107     print_loads(false, logp);
108 }
109
110 process::~process()
111 {
112     delete lb_thread;
113     proc_mutex->acquire();
114     total_load_exit += real_load;
115     proc_mutex->release();
116     xbt_assert(received_load == 0.0,
117                "received_load is %g, but should be 0.0 !", received_load);
118     if (opt::log_rate < 0)
119         return;
120     XBT_INFO("Final load after %d:%d:%d iterations: %g",
121              lb_iter, comp_iter, all_comp_iter, real_load);
122     if (convergence >= 0.0)
123         XBT_INFO("Convergence within %g%% was achieved at time %g",
124                  average_load_ratio, convergence);
125     else
126         XBT_INFO("Convergence within %g%% was not achieved",
127                  average_load_ratio);
128     XBT_VERB("Expected load was: %g", expected_load);
129     XBT_VERB("Total computation for this process: %g", get_comp_amount());
130     print_loads(true, xbt_log_priority_debug);
131 }
132
133 double process::get_iter_deviation() const
134 {
135     double average_cost = opt::comp_cost(total_load_average); // fixme: get locked?
136     // Do not count idle periods
137     double comp_iter_opt = acc.comp_amount / average_cost;
138 /*
139     // Add iterations that could have been achieved while beeing idle
140     // (kept for documentation)
141     double self_speed = MSG_get_host_speed(MSG_host_self());
142     double average_duration = average_cost / self_speed;
143     comp_iter_opt += idle_duration / average_duration;
144 */
145     return comp_iter - comp_iter_opt;
146 }
147
148 int process::run()
149 {
150     if (opt::log_rate >= 0) {
151         XBT_INFO("Initial load: %g", real_load);
152         XBT_VERB("Initial expected load: %g", expected_load);
153     }
154     XBT_VERB("Starting...");
155     mutex.acquire();
156     lb_thread->start();
157     while (lb_iter <= opt::comp_iter_delay)
158         cond.wait(mutex);
159     mutex.release();
160     double sleep_duration = opt::comp_time_delay - MSG_get_clock();
161     if (sleep_duration > 0.0)
162         MSG_process_sleep(sleep_duration);
163     compute_loop();
164     lb_thread->wait();
165     XBT_VERB("Done.");
166     return 0;
167 }
168
169 void process::load_balance_loop()
170 {
171     double next_iter_after_date = MSG_get_clock() + opt::min_lb_iter_duration;
172     while (still_running()) {
173         if (lb_iter == opt::comp_iter_delay) {
174             mutex.acquire();
175             ++lb_iter;
176             cond.signal();
177             mutex.release();
178         } else {
179             ++lb_iter;
180         }
181
182         ctrl_receive(0.0);
183
184         mutex.acquire();
185         if (!opt::bookkeeping)
186             expected_load = real_load - get_sum_of_to_send();
187         // nothing to do with opt::bookkeeping
188
189         if (opt::log_rate && lb_iter % opt::log_rate == 0) {
190             XBT_INFO("(%u:%u:%u) current load: %g",
191                      lb_iter, comp_iter, all_comp_iter, real_load);
192             XBT_VERB("... expected load: %g", expected_load);
193         }
194
195         if (expected_load > 0.0)
196             load_balance();
197
198         print_loads(true, xbt_log_priority_debug);
199
200         // send
201         comm.ctrl_flush(false);
202         for (neighbor& n : neigh)
203             ctrl_send(n);
204         prev_load_broadcast = expected_load;
205         mutex.release();
206
207         sleep_until_date(next_iter_after_date, opt::min_lb_iter_duration);
208     }
209
210     XBT_VERB("Going to finalize for %s...", __func__);
211     XBT_DEBUG("send CTRL_CLOSE to %zu neighbor%s",
212               neigh.size(), ESSE(neigh.size()));
213     for (neighbor& n : neigh)
214         ctrl_close(n);
215     while (ctrl_close_pending) {
216         comm.ctrl_flush(false);
217         XBT_DEBUG("waiting for %d CTRL_CLOSE", ctrl_close_pending);
218         ctrl_receive(-1.0);
219     }
220     comm.ctrl_flush(true);
221 }
222
223 void process::compute_loop()
224 {
225     double next_iter_after_date = MSG_get_clock() + opt::min_comp_iter_duration;
226     double idle_since_date = 0.0;
227     while (still_running()) {
228         // receive
229         // if there is something to compute, do not block
230         // else, block the duration of an *lb* iteration
231         data_receive(real_load > 0.0 ? 0.0 : opt::min_lb_iter_duration);
232
233         // send
234         comm.data_flush(false);
235         mutex.acquire();
236         real_load += received_load;
237         received_load = 0.0;
238         for (neighbor& n : neigh)
239             data_send(n);
240         mutex.release();
241
242         ++all_comp_iter;
243         if (real_load == 0.0)
244             continue;
245
246         convergence_check();
247
248         // compute
249         idle_duration += MSG_get_clock() - idle_since_date;
250         ++comp_iter;
251         double flops = opt::comp_cost(real_load);
252         msg_task_t task = MSG_task_create("computation", flops, 0.0, NULL);
253         // MSG_task_set_category(task, TRACE_CAT_COMP);
254         XBT_DEBUG("compute %g flop%s", flops, ESSE(flops));
255         MSG_task_execute(task);
256         add_comp_amount(flops);
257         MSG_task_destroy(task);
258
259         idle_since_date = MSG_get_clock();
260
261         sleep_until_date(next_iter_after_date, opt::min_comp_iter_duration);
262     }
263
264     XBT_VERB("Going to finalize for %s...", __func__);
265     // Note: idle duration is not counted during finalization
266     finalizing = true;
267     XBT_DEBUG("send DATA_CLOSE to %zu neighbor%s",
268               neigh.size(), ESSE(neigh.size()));
269     for (neighbor& n : neigh)
270         data_close(n);
271     while (data_close_pending) {
272         comm.data_flush(false);
273         XBT_DEBUG("waiting for %d DATA_CLOSE", data_close_pending);
274         data_receive(-1.0);
275     }
276     real_load += received_load;
277     received_load = 0.0;
278     proc_mutex->acquire();
279     total_load_running -= real_load;
280     proc_mutex->release();
281     convergence_check();
282     comm.data_flush(true);
283 }
284
285 void process::convergence_check()
286 {
287     double average = total_load_average; // fixme: get locked?
288     double load_diff = std::fabs(real_load - average);
289     bool converged = load_diff <= load_diff_threshold;
290
291     if (converged) {
292         if (convergence < 0) {
293             XBT_VERB("current load has converged: %g (%.4g%%)",
294                      real_load,  100.0 * load_diff / average);
295             convergence = MSG_get_clock();
296             local_convergence_counter = opt::exit_on_convergence;
297         }
298         if (local_convergence_counter > 0 && --local_convergence_counter == 0)
299                 --convergence_counter;
300     } else {
301         if (convergence >= 0.0) {
302             XBT_VERB("current load has diverged: %g (%.4g%%)",
303                      real_load, 100.0 * load_diff / average);
304             convergence = -1.0;
305             if (local_convergence_counter == 0)
306                 ++convergence_counter;
307         }
308     }
309 }
310
311 bool process::still_running()
312 {
313     static bool last_status = true;
314
315     if (!last_status) {
316         /* nop */
317
318     } else if (opt::exit_request) {
319         XBT_VERB("Global exit requested");
320         last_status = false;
321
322     } else if (opt::time_limit && MSG_get_clock() >= opt::time_limit) {
323         XBT_VERB("Reached time limit: %g/%g", MSG_get_clock(), opt::time_limit);
324         last_status = false;
325
326     } else if (opt::lb_maxiter && lb_iter >= opt::lb_maxiter) {
327         XBT_VERB("Reached lb_maxiter: %d/%d", lb_iter, opt::lb_maxiter);
328         last_status = false;
329
330     } else if (opt::comp_maxiter && comp_iter >= opt::comp_maxiter) {
331         XBT_VERB("Reached comp_maxiter: %d/%d", comp_iter, opt::comp_maxiter);
332         last_status = false;
333
334     } else if (opt::exit_on_convergence && convergence_counter == 0) {
335         XBT_VERB("Global convergence detected");
336         last_status = false;
337
338     } else if (opt::exit_on_close && close_received) {
339         XBT_VERB("Close received");
340         last_status = false;
341
342     } else if (real_load == 0.0 && !data_close_pending) {
343         XBT_VERB("I'm a poor lonesome process, and I have no load...");
344         last_status = false;
345
346     } else if (100.0 * total_load_running / total_load_init <=
347                opt::load_ratio_threshold) { // fixme: get locked?
348         // fixme: this check should be implemented with a distributed
349         // algorithm, and not a shared global variable!
350         XBT_VERB("No more load to balance in system.");
351         last_status = false;
352     }
353
354     return last_status;
355 }
356
357 double process::get_sum_of_to_send() const
358 {
359     return std::accumulate(neigh.begin(), neigh.end(), 0.0,
360                            [](double x, const neighbor& neigh) {
361                                return x + neigh.get_to_send();
362                            });
363 }
364
365 void process::load_balance()
366 {
367     if (lb_iter == 1)           // warn only once
368         XBT_WARN("process::load_balance() is a no-op!");
369 }
370
371 void process::send(neighbor& nb, double amount)
372 {
373     expected_load -= amount;
374     nb.set_to_send(nb.get_to_send() + amount);
375     nb.set_load(nb.get_load() + amount);
376 }
377
378 void process::ctrl_send(neighbor& nb)
379 {
380     double info_to_send = expected_load;
381     double debt_to_send;
382     if (opt::bookkeeping) {     // bookkeeping
383         debt_to_send = nb.get_to_send();
384         if (debt_to_send > 0.0) {
385             nb.set_to_send(0.0);
386             nb.set_debt(nb.get_debt() + debt_to_send);
387         }
388     } else {                    // !bookkeeping
389         debt_to_send = 0.0;
390     }
391     if (info_to_send != prev_load_broadcast || debt_to_send > 0.0) {
392         message* msg = new message(message::CTRL, info_to_send, debt_to_send);
393         add_ctrl_send_mesg(msg->get_size());
394         comm.ctrl_send(nb.get_ctrl_mbox(), msg);
395     }
396 }
397
398 double process::compute_load_to_send(double desired)
399 {
400     if (opt::integer_transfer)
401         desired = std::floor(desired);
402     return desired >= opt::min_transfer_amount ? desired : 0.0;
403 }
404
405 void process::data_send(neighbor& nb)
406 {
407     double load_to_send;
408     if (opt::bookkeeping) {     // bookkeeping
409         double excess_load;     // load amount we are able to send
410         if (opt::egocentric)
411             excess_load = std::max(0.0, real_load - expected_load);
412         else
413             excess_load = real_load;
414
415         double balance;
416         if (nb.get_credit() > 0.0)
417             balance = nb.get_debt() - nb.get_credit();
418         else
419             balance = nb.get_debt();
420         load_to_send = std::min(excess_load,
421                                 std::max(0.0, balance));
422
423         // adjust load to send (rounding, truncation, etc.)
424         load_to_send = compute_load_to_send(load_to_send);
425         if (load_to_send > 0.0)
426             nb.set_debt(nb.get_debt() - load_to_send);
427     } else {                    // !bookkeeping
428         load_to_send = compute_load_to_send(nb.get_to_send());
429         if (load_to_send > 0.0)
430             nb.set_to_send(nb.get_to_send() - load_to_send);
431     }
432     real_load -= load_to_send;
433     while (load_to_send > 0.0) {
434         double amount;
435         if (opt::max_transfer_amount)
436             amount = std::min(load_to_send, opt::max_transfer_amount);
437         else
438             amount = load_to_send;
439         message* msg = new message(message::DATA, amount);
440         add_data_send_mesg(msg->get_size());
441         comm.data_send(nb.get_data_mbox(), msg);
442         load_to_send -= amount;
443     }
444 }
445
446 void process::ctrl_close(neighbor& nb)
447 {
448     comm.ctrl_send(nb.get_ctrl_mbox(), new message(message::CTRL_CLOSE, 0.0));
449 }
450
451 void process::data_close(neighbor& nb)
452 {
453     comm.data_send(nb.get_data_mbox(), new message(message::DATA_CLOSE, 0.0));
454 }
455
456 void process::ctrl_receive(double timeout)
457 {
458     message* msg;
459     msg_host_t from;
460
461     XBT_DEBUG("%sblocking receive on ctrl (%g)", "\0non-" + !timeout, timeout);
462     while (ctrl_close_pending && comm.ctrl_recv(msg, from, timeout)) {
463         if (msg->get_type() != message::CTRL_CLOSE)
464             add_ctrl_recv_mesg(msg->get_size());
465         handle_message(msg, from);
466         timeout = 0.0;
467     }
468 }
469
470 void process::data_receive(double timeout)
471 {
472     message* msg;
473     msg_host_t from;
474
475     XBT_DEBUG("%sblocking receive on data (%g)", "\0non-" + !timeout, timeout);
476     while (data_close_pending && comm.data_recv(msg, from, timeout)) {
477         if (msg->get_type() != message::DATA_CLOSE)
478             add_data_recv_mesg(msg->get_size());
479         handle_message(msg, from);
480         timeout = 0.0;
481     }
482 }
483
484 void process::handle_message(message* msg, msg_host_t from)
485 {
486     switch (msg->get_type()) {
487     case message::CTRL: {
488         neighbor* n = rev_neigh[from];
489         n->set_load(msg->get_amount() + n->get_to_send());
490         if (opt::bookkeeping) {
491             double credit = msg->get_credit();
492             expected_load += credit;
493             n->set_credit(n->get_credit() + credit);
494         }
495         break;
496     }
497     case message::DATA: {
498         neighbor* n = rev_neigh[from];
499         double ld = msg->get_amount();
500         received_load += ld;
501         n->set_credit(n->get_credit() - ld);
502         break;
503     }
504     case message::CTRL_CLOSE:
505         ctrl_close_pending--;
506         close_received = true;
507         break;
508     case message::DATA_CLOSE:
509         data_close_pending--;
510         close_received = true;
511         break;
512     }
513     delete msg;
514 }
515
516 void process::print_loads(bool verbose,
517                           e_xbt_log_priority_t logp,
518                           xbt_log_category_t cat) const
519 {
520     if (!_XBT_LOG_ISENABLEDV((*cat), logp))
521         return;
522     XBT_XCLOG(cat, logp, "My load: %g (real); %g (expected).  Neighbor loads:",
523               real_load, expected_load);
524     for (const neighbor& n : neigh)
525         n.print(verbose, logp, cat);
526 }
527
528 void process::print_loads_p(bool verbose,
529                             e_xbt_log_priority_t logp,
530                             xbt_log_category_t cat) const
531 {
532     if (!_XBT_LOG_ISENABLEDV((*cat), logp))
533         return;
534     XBT_XCLOG(cat, logp, "My load: %g (real); %g (expected).  Neighbor loads:",
535               real_load, expected_load);
536     for (const neighbor* n : pneigh)
537         n->print(verbose, logp, cat);
538 }
539
540 #undef print_loads_generic
541
542 // Local variables:
543 // mode: c++
544 // End: