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

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