Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Fix bug found at ptask experiments
[simgrid.git] / src / kernel / lmm / bmf.cpp
1 /* Copyright (c) 2007-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 "src/kernel/lmm/bmf.hpp"
7 #include <eigen3/Eigen/LU>
8 #include <iostream>
9 #include <numeric>
10 #include <sstream>
11
12 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(ker_bmf, kernel, "Kernel BMF solver");
13
14 int sg_bmf_max_iterations = 1000; /* Change this with --cfg=bmf/max-iterations:VALUE */
15
16 namespace simgrid {
17 namespace kernel {
18 namespace lmm {
19
20 AllocationGenerator::AllocationGenerator(Eigen::MatrixXd A) : A_(std::move(A)), alloc_(A_.cols(), 0)
21 {
22   // got a first valid allocation
23   for (size_t p = 0; p < alloc_.size(); p++) {
24     for (int r = 0; r < A_.rows(); r++) {
25       if (A_(r, p) > 0) {
26         alloc_[p] = r;
27         break;
28       }
29     }
30   }
31 }
32
33 bool AllocationGenerator::next(std::vector<int>& next_alloc)
34 {
35   if (first_) {
36     next_alloc = alloc_;
37     first_     = false;
38     return true;
39   }
40
41   int n_resources = A_.rows();
42   size_t idx      = 0;
43   while (idx < alloc_.size()) {
44     alloc_[idx] = (++alloc_[idx]) % n_resources;
45     if (alloc_[idx] == 0) {
46       idx++;
47       continue;
48     } else {
49       idx = 0;
50     }
51     if (A_(alloc_[idx], idx) > 0) {
52       next_alloc = alloc_;
53       return true;
54     }
55   }
56   return false;
57 }
58
59 /*****************************************************************************/
60
61 BmfSolver::BmfSolver(Eigen::MatrixXd A, Eigen::MatrixXd maxA, Eigen::VectorXd C, std::vector<bool> shared,
62                      Eigen::VectorXd phi)
63     : A_(std::move(A))
64     , maxA_(std::move(maxA))
65     , C_(std::move(C))
66     , C_shared_(std::move(shared))
67     , phi_(std::move(phi))
68     , gen_(A_)
69 {
70   xbt_assert(max_iteration_ > 0,
71              "Invalid number of iterations for BMF solver. Please check your \"bmf/max-iterations\" configuration.");
72   xbt_assert(A_.cols() == maxA_.cols(), "Invalid number of cols in matrix A (%ld) or maxA (%ld)", A_.cols(),
73              maxA_.cols());
74   xbt_assert(A_.cols() == static_cast<long>(phi_.size()), "Invalid size of phi vector (%ld)", phi_.size());
75   xbt_assert(static_cast<long>(C_shared_.size()) == C_.size(), "Invalid size param shared (%zu)", C_shared_.size());
76 }
77
78 template <typename T> std::string BmfSolver::debug_eigen(const T& obj) const
79 {
80   std::stringstream debug;
81   debug << obj;
82   return debug.str();
83 }
84
85 template <typename C> std::string BmfSolver::debug_vector(const C& container) const
86 {
87   std::stringstream debug;
88   std::copy(container.begin(), container.end(),
89             std::ostream_iterator<typename std::remove_reference<decltype(container)>::type::value_type>(debug, " "));
90   return debug.str();
91 }
92
93 std::string BmfSolver::debug_alloc(const allocation_map_t& alloc) const
94 {
95   std::stringstream debug;
96   for (const auto& e : alloc) {
97     debug << "{" + std::to_string(e.first) + ": [" + debug_vector(e.second) + "]}, ";
98   }
99   return debug.str();
100 }
101
102 double BmfSolver::get_resource_capacity(int resource, const std::vector<int>& bounded_players) const
103 {
104   double capacity = C_[resource];
105   if (not C_shared_[resource])
106     return capacity;
107
108   for (int p : bounded_players) {
109     capacity -= A_(resource, p) * phi_[p];
110   }
111   return std::max(0.0, capacity);
112 }
113
114 std::vector<int> BmfSolver::alloc_map_to_vector(const allocation_map_t& alloc) const
115 {
116   std::vector<int> alloc_by_player(A_.cols(), -1);
117   for (auto it : alloc) {
118     for (auto p : it.second) {
119       alloc_by_player[p] = it.first;
120     }
121   }
122   return alloc_by_player;
123 }
124
125 std::vector<int> BmfSolver::get_bounded_players(const allocation_map_t& alloc) const
126 {
127   std::vector<int> bounded_players;
128   for (const auto& e : alloc) {
129     if (e.first == NO_RESOURCE) {
130       bounded_players.insert(bounded_players.end(), e.second.begin(), e.second.end());
131     }
132   }
133   return bounded_players;
134 }
135
136 Eigen::VectorXd BmfSolver::equilibrium(const allocation_map_t& alloc) const
137 {
138   int n_players       = A_.cols();
139   Eigen::MatrixXd A_p = Eigen::MatrixXd::Zero(n_players, n_players); // square matrix with number of players
140   Eigen::VectorXd C_p = Eigen::VectorXd::Zero(n_players);
141
142   int row = 0;
143   auto bounded_players = get_bounded_players(alloc);
144   for (const auto& e : alloc) {
145     // add one row for the resource with A[r,]
146     int cur_resource = e.first;
147     if (cur_resource == NO_RESOURCE)
148       continue;
149
150     if (C_shared_[cur_resource]) {
151       /* shared resource: fairly share it between players */
152       A_p.row(row) = A_.row(cur_resource);
153       C_p[row]     = get_resource_capacity(cur_resource, bounded_players);
154       row++;
155       if (e.second.size() > 1) {
156         // if 2 players have chosen the same resource
157         // they must have a fair sharing of this resource, adjust A_p and C_p accordingly
158         auto it = e.second.begin();
159         int i   = *it; // first player
160         /* for each other player sharing this resource */
161         for (++it; it != e.second.end(); ++it) {
162           /* player i and k on this resource j: so maxA_ji*rho_i - maxA_jk*rho_k = 0 */
163           int k       = *it;
164           C_p[row]    = 0;
165           A_p(row, i) = maxA_(cur_resource, i);
166           A_p(row, k) = -maxA_(cur_resource, k);
167           row++;
168         }
169       }
170     } else {
171       /* not shared resource, each player can receive the full capacity of the resource */
172       for (int i : e.second) {
173         C_p[row]    = get_resource_capacity(cur_resource, bounded_players);
174         A_p(row, i) = A_(cur_resource, i);
175         row++;
176       }
177     }
178   }
179   /* clear players which are externally bounded */
180   for (int p : bounded_players) {
181     A_p.col(p).setZero();
182   }
183
184   XBT_DEBUG("A':\n%s", debug_eigen(A_p).c_str());
185
186   XBT_DEBUG("C':\n%s", debug_eigen(C_p).c_str());
187   Eigen::VectorXd rho = Eigen::FullPivLU<Eigen::MatrixXd>(A_p).solve(C_p);
188   for (int p : bounded_players) {
189     rho[p] = phi_[p];
190   }
191   return rho;
192 }
193
194 bool BmfSolver::disturb_allocation(allocation_map_t& alloc, std::vector<int>& alloc_by_player)
195 {
196   while (gen_.next(alloc_by_player)) {
197     if (allocations_.find(alloc_by_player) == allocations_.end()) {
198       allocations_.clear();
199       allocations_.insert(alloc_by_player);
200       alloc.clear();
201       for (size_t p = 0; p < alloc_by_player.size(); p++) {
202         alloc[alloc_by_player[p]].insert(p);
203       }
204       return false;
205     }
206   }
207   return true;
208 }
209
210 bool BmfSolver::get_alloc(const Eigen::VectorXd& fair_sharing, const allocation_map_t& last_alloc,
211                           allocation_map_t& alloc, bool initial)
212 {
213   alloc.clear();
214   for (int player_idx = 0; player_idx < A_.cols(); player_idx++) {
215     int selected_resource = NO_RESOURCE;
216     double bound          = phi_[player_idx];
217     double min_share      = (bound <= 0 || initial) ? -1 : bound;
218     for (int cnst_idx = 0; cnst_idx < A_.rows(); cnst_idx++) {
219       if (A_(cnst_idx, player_idx) <= 0.0)
220         continue;
221
222       double share = fair_sharing[cnst_idx] / A_(cnst_idx, player_idx);
223       if (min_share == -1 || share < min_share) {
224
225         selected_resource = cnst_idx;
226         min_share         = share;
227       }
228     }
229     alloc[selected_resource].insert(player_idx);
230   }
231   bool is_stable = (alloc == last_alloc);
232   if (is_stable)
233     return true;
234
235   std::vector<int> alloc_by_player      = alloc_map_to_vector(alloc);
236   auto ret = allocations_.insert(alloc_by_player);
237   /* oops, allocation already tried, let's pertube it a bit */
238   if (not ret.second) {
239     XBT_DEBUG("Allocation already tried: %s", debug_alloc(alloc).c_str());
240     return disturb_allocation(alloc, alloc_by_player);
241   }
242   return false;
243 }
244
245 void BmfSolver::set_fair_sharing(const allocation_map_t& alloc, const Eigen::VectorXd& rho,
246                                  Eigen::VectorXd& fair_sharing) const
247 {
248   std::vector<int> bounded_players = get_bounded_players(alloc);
249
250   for (int r = 0; r < fair_sharing.size(); r++) {
251     auto it = alloc.find(r);
252     if (it != alloc.end()) {              // resource selected by some player, fair share depends on rho
253       int player = *(it->second.begin()); // equilibrium assures that every player receives the same, use one of them to
254                                           // calculate the fair sharing for resource r
255       fair_sharing[r] = A_(r, player) * rho[player];
256     } else { // nobody selects this resource, fair_sharing depends on resource saturation
257       // resource r is saturated (A[r,*] * rho > C), divide it among players
258       double consumption_r = A_.row(r) * rho;
259       double_update(&consumption_r, C_[r], sg_maxmin_precision);
260       if (consumption_r > 0.0) {
261         int n_players   = (A_.row(r).array() > 0).count();
262         fair_sharing[r] = C_[r] / n_players;
263       } else {
264         fair_sharing[r] = get_resource_capacity(r, bounded_players);
265       }
266     }
267   }
268 }
269
270 bool BmfSolver::is_bmf(const Eigen::VectorXd& rho) const
271 {
272   bool bmf = true;
273
274   // 1) the capacity of all resources is respected
275   Eigen::VectorXd shared(C_shared_.size());
276   for (int j = 0; j < shared.size(); j++)
277     shared[j] = C_shared_[j] ? 1.0 : 0.0;
278
279   Eigen::VectorXd remaining = (A_ * rho) - C_;
280   remaining                 = remaining.array() * shared.array(); // ignore non shared resources
281   bmf                       = bmf && (not std::any_of(remaining.data(), remaining.data() + remaining.size(),
282                                 [](double v) { return double_positive(v, sg_maxmin_precision); }));
283
284   // 3) every player receives maximum share in at least 1 saturated resource
285   // due to subflows, compare with the maximum consumption and not the A matrix
286   Eigen::MatrixXd usage =
287       maxA_.array().rowwise() * rho.transpose().array(); // usage_ji: indicates the usage of player i on resource j
288
289   XBT_DEBUG("Usage_ji considering max consumption:\n%s", debug_eigen(usage).c_str());
290   auto max_share = usage.rowwise().maxCoeff(); // max share for each resource j
291
292   // matrix_ji: boolean indicating player p has the maximum share at resource j
293   Eigen::MatrixXi player_max_share =
294       ((usage.array().colwise() - max_share.array()).abs() <= sg_maxmin_precision).cast<int>();
295   // but only saturated resources must be considered
296   Eigen::VectorXi saturated = ((remaining.array().abs() <= sg_maxmin_precision)).cast<int>();
297   XBT_DEBUG("Saturated_j resources:\n%s", debug_eigen(saturated).c_str());
298   player_max_share.array().colwise() *= saturated.array();
299
300   // just check if it has received at least it's bound
301   for (int p = 0; p < rho.size(); p++) {
302     if (double_equals(rho[p], phi_[p], sg_maxmin_precision)) {
303       player_max_share(0, p) = 1; // it doesn't really matter, just to say that it's a bmf
304       saturated[0]           = 1;
305     }
306   }
307
308   // 2) at least 1 resource is saturated
309   bmf = bmf && (saturated.array() == 1).any();
310
311   XBT_DEBUG("Player_ji usage of saturated resources:\n%s", debug_eigen(player_max_share).c_str());
312   // for all columns(players) it has to be the max at least in 1
313   bmf = bmf && (player_max_share.colwise().sum().all() >= 1);
314   return bmf;
315 }
316
317 Eigen::VectorXd BmfSolver::solve()
318 {
319   XBT_DEBUG("Starting BMF solver");
320
321   XBT_DEBUG("A:\n%s", debug_eigen(A_).c_str());
322   XBT_DEBUG("maxA:\n%s", debug_eigen(maxA_).c_str());
323   XBT_DEBUG("C:\n%s", debug_eigen(C_).c_str());
324
325   /* no flows to share, just returns */
326   if (A_.cols() == 0)
327     return {};
328
329   int it            = 0;
330   auto fair_sharing = C_;
331
332   /* BMF allocation for each player (current and last one) stop when are equal */
333   allocation_map_t last_alloc, cur_alloc;
334   Eigen::VectorXd rho;
335
336   while (it < max_iteration_ && not get_alloc(fair_sharing, last_alloc, cur_alloc, it == 0)) {
337     last_alloc = cur_alloc;
338     XBT_DEBUG("BMF: iteration %d", it);
339     XBT_DEBUG("B (current allocation): %s", debug_alloc(cur_alloc).c_str());
340
341     // solve inv(A)*rho = C
342     rho = equilibrium(cur_alloc);
343     XBT_DEBUG("rho:\n%s", debug_eigen(rho).c_str());
344
345     // get fair sharing for each resource
346     set_fair_sharing(cur_alloc, rho, fair_sharing);
347     XBT_DEBUG("Fair sharing vector (per resource):\n%s", debug_eigen(fair_sharing).c_str());
348
349     // get new allocation for players
350     it++;
351   }
352
353   /* Not mandatory but a safe check to assure we have a proper solution */
354   if (not is_bmf(rho)) {
355     fprintf(stderr, "Unable to find a BMF allocation for your system.\n"
356                     "You may try to increase the maximum number of iterations performed by BMF solver "
357                     "(\"--cfg=bmf/max-iterations\").\n"
358                     "Additionally, you could decrease numerical precision (\"--cfg=surf/precision\").\n");
359     fprintf(stderr, "Internal states (after %d iterations):\n", it);
360     fprintf(stderr, "A:\n%s\n", debug_eigen(A_).c_str());
361     fprintf(stderr, "maxA:\n%s\n", debug_eigen(maxA_).c_str());
362     fprintf(stderr, "C:\n%s\n", debug_eigen(C_).c_str());
363     fprintf(stderr, "C_shared:\n%s\n", debug_vector(C_shared_).c_str());
364     fprintf(stderr, "phi:\n%s\n", debug_eigen(phi_).c_str());
365     fprintf(stderr, "rho:\n%s\n", debug_eigen(rho).c_str());
366     xbt_abort();
367   }
368
369   XBT_DEBUG("BMF done after %d iterations", it);
370   return rho;
371 }
372
373 /*****************************************************************************/
374
375 void BmfSystem::get_flows_data(int number_cnsts, Eigen::MatrixXd& A, Eigen::MatrixXd& maxA, Eigen::VectorXd& phi)
376 {
377   A.resize(number_cnsts, variable_set.size());
378   A.setZero();
379   maxA.resize(number_cnsts, variable_set.size());
380   maxA.setZero();
381   phi.resize(variable_set.size());
382
383   int var_idx = 0;
384   for (Variable& var : variable_set) {
385     if (var.sharing_penalty_ <= 0)
386       continue;
387     bool active = false;
388     bool linked = false; // variable is linked to some constraint (specially for selective_update)
389     for (const Element& elem : var.cnsts_) {
390       boost::intrusive::list_member_hook<>& cnst_hook = selective_update_active
391                                                             ? elem.constraint->modified_constraint_set_hook_
392                                                             : elem.constraint->active_constraint_set_hook_;
393       if (not cnst_hook.is_linked())
394         continue;
395       /* active and linked variable, lets check its consumption */
396       linked             = true;
397       double consumption = elem.consumption_weight;
398       if (consumption > 0) {
399         int cnst_idx = cnst2idx_[elem.constraint];
400         A(cnst_idx, var_idx) += consumption;
401         // a variable with double penalty must receive half share, so it max weight is greater
402         maxA(cnst_idx, var_idx) = std::max(maxA(cnst_idx, var_idx), elem.max_consumption_weight * var.sharing_penalty_);
403         active                  = true;
404       }
405     }
406     /* skip variables not linked to any modified or active constraint */
407     if (not linked)
408       continue;
409     if (active) {
410       phi[var_idx]      = var.get_bound();
411       idx2Var_[var_idx] = &var;
412       var_idx++;
413     } else {
414       var.value_ = 1; // assign something by default for tasks with 0 consumption
415     }
416   }
417   // resize matrix to active variables only
418   A.conservativeResize(Eigen::NoChange_t::NoChange, var_idx);
419   maxA.conservativeResize(Eigen::NoChange_t::NoChange, var_idx);
420   phi.conservativeResize(var_idx);
421 }
422
423 template <class CnstList>
424 void BmfSystem::get_constraint_data(const CnstList& cnst_list, Eigen::VectorXd& C, std::vector<bool>& shared)
425 {
426   C.resize(cnst_list.size());
427   shared.resize(cnst_list.size());
428   cnst2idx_.clear();
429   int cnst_idx = 0;
430   for (const Constraint& cnst : cnst_list) {
431     C(cnst_idx)      = cnst.bound_;
432     if (cnst.get_sharing_policy() == Constraint::SharingPolicy::NONLINEAR && cnst.dyn_constraint_cb_) {
433       C(cnst_idx) = cnst.dyn_constraint_cb_(cnst.bound_, cnst.concurrency_current_);
434       if (not warned_nonlinear_) {
435         XBT_WARN("You are using dynamic constraint bound with parallel tasks and BMF model."
436                  " The BMF solver assumes that all flows (and subflows) are always active and executing."
437                  " This is quite pessimist, specially considering parallel tasks with small subflows."
438                  " Analyze your results with caution.");
439         warned_nonlinear_ = true;
440       }
441     }
442     cnst2idx_[&cnst] = cnst_idx;
443     // FATPIPE links aren't really shared
444     shared[cnst_idx] = (cnst.sharing_policy_ != Constraint::SharingPolicy::FATPIPE);
445     cnst_idx++;
446   }
447 }
448
449 void BmfSystem::solve()
450 {
451   if (modified_) {
452     if (selective_update_active)
453       bmf_solve(modified_constraint_set);
454     else
455       bmf_solve(active_constraint_set);
456   }
457 }
458
459 template <class CnstList> void BmfSystem::bmf_solve(const CnstList& cnst_list)
460 {
461   /* initialize players' weight and constraint matrices */
462   idx2Var_.clear();
463   cnst2idx_.clear();
464   Eigen::MatrixXd A, maxA;
465   Eigen::VectorXd C, bounds;
466   std::vector<bool> shared;
467   get_constraint_data(cnst_list, C, shared);
468   get_flows_data(C.size(), A, maxA, bounds);
469
470   auto solver = BmfSolver(std::move(A), std::move(maxA), std::move(C), std::move(shared), std::move(bounds));
471   auto rho    = solver.solve();
472
473   if (rho.size() == 0)
474     return;
475
476   /* setting rhos */
477   for (int i = 0; i < rho.size(); i++) {
478     idx2Var_[i]->value_ = rho[i];
479   }
480
481   print();
482 }
483
484 } // namespace lmm
485 } // namespace kernel
486 } // namespace simgrid