Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Support for bounded actions in BMF solver
[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 <sstream>
10
11 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(ker_bmf, kernel, "Kernel BMF solver");
12
13 void simgrid::kernel::lmm::BmfSystem::set_matrix_A()
14 {
15   A_.resize(active_constraint_set.size(), variable_set.size());
16   A_.setZero();
17   maxA_.resize(active_constraint_set.size(), variable_set.size());
18
19   int var_idx = 0;
20   for (Variable& var : variable_set) {
21     if (var.sharing_penalty_ <= 0)
22       continue;
23     bool active = false;
24     var.value_  = 1; // assign something by default for tasks with 0 consumption
25     for (const Element& elem : var.cnsts_) {
26       double consumption = elem.consumption_weight;
27       if (consumption > 0) {
28         int cnst_idx             = cnst2idx_[elem.constraint];
29         A_(cnst_idx, var_idx)    = consumption;
30         maxA_(cnst_idx, var_idx) = elem.max_consumption_weight;
31         active                   = true;
32       }
33     }
34     if (active) {
35       idx2Var_[var_idx] = &var;
36       var_idx++;
37     }
38   }
39   // resize matrix to active variables only
40   A_.conservativeResize(Eigen::NoChange_t::NoChange, var_idx);
41   maxA_.conservativeResize(Eigen::NoChange_t::NoChange, var_idx);
42 }
43
44 void simgrid::kernel::lmm::BmfSystem::set_vector_C()
45 {
46   C_.resize(active_constraint_set.size());
47   cnst2idx_.clear();
48   int cnst_idx = 0;
49   for (const Constraint& cnst : active_constraint_set) {
50     C_(cnst_idx)     = cnst.bound_;
51     cnst2idx_[&cnst] = cnst_idx;
52     cnst_idx++;
53   }
54 }
55
56 std::unordered_map<int, std::vector<int>>
57 simgrid::kernel::lmm::BmfSystem::get_alloc(const Eigen::VectorXd& fair_sharing, bool initial) const
58 {
59   std::unordered_map<int, std::vector<int>> alloc;
60   for (int player_idx = 0; player_idx < A_.cols(); player_idx++) {
61     int selected_resource = NO_RESOURCE;
62     double bound          = idx2Var_.at(player_idx)->get_bound();
63     double min_share      = (bound <= 0 || initial) ? -1 : bound;
64     for (int cnst_idx = 0; cnst_idx < A_.rows(); cnst_idx++) {
65       if (A_(cnst_idx, player_idx) <= 0.0)
66         continue;
67
68       double share = fair_sharing[cnst_idx] / A_(cnst_idx, player_idx);
69       if (min_share == -1 || double_positive(min_share - share, sg_maxmin_precision)) {
70         selected_resource = cnst_idx;
71         min_share         = share;
72       }
73     }
74     alloc[selected_resource].push_back(player_idx);
75   }
76   return alloc;
77 }
78
79 void simgrid::kernel::lmm::BmfSystem::set_fair_sharing(const std::unordered_map<int, std::vector<int>>& alloc,
80                                                        const Eigen::VectorXd& rho, Eigen::VectorXd& fair_sharing) const
81 {
82   for (int r = 0; r < fair_sharing.size(); r++) {
83     auto it = alloc.find(r);
84     if (it != alloc.end()) {      // resource selected by some player, fair share depends on rho
85       int player = it->second[0]; // equilibrium assures that every player receives the same, use one of them to
86                                   // calculate the fair sharing for resource r
87       fair_sharing[r] = A_(r, player) * rho[player];
88     } else { // nobody selects this resource, fair_sharing depends on resource saturation
89       // resource r is saturated (A[r,*] * rho > C), divide it among players
90       double consumption_r = A_.row(r) * rho;
91       double_update(&consumption_r, C_[r], sg_maxmin_precision);
92       if (consumption_r > 0.0) {
93         int n_players   = std::count_if(A_.row(r).data(), A_.row(r).data() + A_.row(r).size(),
94                                       [](double v) { return double_positive(v, sg_maxmin_precision); });
95         fair_sharing[r] = C_[r] / n_players;
96       } else {
97         fair_sharing[r] = C_[r];
98       }
99     }
100   }
101 }
102
103 template <typename T> std::string simgrid::kernel::lmm::BmfSystem::debug_eigen(const T& obj) const
104 {
105   std::stringstream debug;
106   debug << obj;
107   return debug.str();
108 }
109
110 template <typename T> std::string simgrid::kernel::lmm::BmfSystem::debug_vector(const std::vector<T>& vector) const
111 {
112   std::stringstream debug;
113   std::copy(vector.begin(), vector.end(), std::ostream_iterator<T>(debug, " "));
114   return debug.str();
115 }
116
117 std::string simgrid::kernel::lmm::BmfSystem::debug_alloc(const std::unordered_map<int, std::vector<int>>& alloc) const
118 {
119   std::stringstream debug;
120   for (const auto& e : alloc) {
121     debug << "{" + std::to_string(e.first) + ": [" + debug_vector(e.second) + "]}, ";
122   }
123   return debug.str();
124 }
125
126 double simgrid::kernel::lmm::BmfSystem::get_resource_capacity(int resource,
127                                                               const std::vector<int>& bounded_players) const
128 {
129   double capacity = C_[resource];
130   for (int p : bounded_players) {
131     capacity -= A_(resource, p) * idx2Var_.at(p)->get_bound();
132   }
133   return capacity;
134 }
135
136 Eigen::VectorXd
137 simgrid::kernel::lmm::BmfSystem::equilibrium(const std::unordered_map<int, std::vector<int>>& alloc) const
138 {
139   int n_players       = A_.cols();
140   Eigen::MatrixXd A_p = Eigen::MatrixXd::Zero(n_players, n_players); // square matrix with number of players
141   Eigen::VectorXd C_p = Eigen::VectorXd::Zero(n_players);
142
143   // iterate over alloc to verify if 2 players have chosen the same resource
144   // if so, they must have a fair sharing of this resource, adjust A_p and C_p accordingly
145   int last_row = n_players - 1;
146   int first_row = 0;
147   std::vector<int> bounded_players;
148   for (const auto& e : alloc) {
149     // add one row for the resource with A[r,]
150     int cur_resource   = e.first;
151     if (cur_resource == NO_RESOURCE) {
152       bounded_players.insert(bounded_players.end(), e.second.begin(), e.second.end());
153       continue;
154     }
155     A_p.row(first_row) = A_.row(cur_resource);
156     C_p[first_row]     = get_resource_capacity(cur_resource, bounded_players);
157     first_row++;
158     if (e.second.size() > 1) {
159       int i = e.second[0];                                 // first player
160       for (size_t idx = 1; idx < e.second.size(); idx++) { // for each other player sharing this resource
161         /* player i and k on this resource j: so maxA_ji*rho_i - maxA_jk*rho_k = 0 */
162         int k            = e.second[idx];
163         C_p[last_row]    = 0;
164         A_p(last_row, i) = maxA_(cur_resource, i);
165         A_p(last_row, k) = -maxA_(cur_resource, k);
166         last_row--;
167       }
168     }
169   }
170   /* clear players which are externally bounded */
171   for (int p : bounded_players) {
172     A_p.col(p).setZero();
173   }
174
175   XBT_DEBUG("A':\n%s", debug_eigen(A_p).c_str());
176
177   XBT_DEBUG("C':\n%s", debug_eigen(C_p).c_str());
178   Eigen::VectorXd rho = Eigen::FullPivLU<Eigen::MatrixXd>(A_p).solve(C_p);
179   for (int p : bounded_players) {
180     rho[p] = idx2Var_.at(p)->get_bound();
181   }
182   return rho;
183 }
184
185 bool simgrid::kernel::lmm::BmfSystem::is_bmf(const Eigen::VectorXd& rho) const
186 {
187   bool bmf = true;
188
189   // 1) the capacity of all resources is respected
190   Eigen::VectorXd remaining = (A_ * rho) - C_;
191   bmf                       = bmf && (not std::any_of(remaining.data(), remaining.data() + remaining.size(),
192                                 [](double v) { return double_positive(v, sg_maxmin_precision); }));
193
194   // 3) every player receives maximum share in at least 1 saturated resource
195   // due to subflows, compare with the maximum consumption and not the A matrix
196   Eigen::MatrixXd usage =
197       maxA_.array().rowwise() * rho.transpose().array(); // usage_ji: indicates the usage of player i on resource j
198
199   XBT_DEBUG("Usage_ji considering max consumption:\n%s", debug_eigen(usage).c_str());
200   auto max_share = usage.rowwise().maxCoeff(); // max share for each resource j
201
202   // matrix_ji: boolean indicating player p has the maximum share at resource j
203   Eigen::MatrixXi player_max_share =
204       ((usage.array().colwise() - max_share.array()).abs() <= sg_maxmin_precision).cast<int>();
205   // but only saturated resources must be considered
206   Eigen::VectorXi saturated = ((remaining.array().abs() <= sg_maxmin_precision)).cast<int>();
207   XBT_DEBUG("Saturated_j resources:\n%s", debug_eigen(saturated).c_str());
208   player_max_share.array().colwise() *= saturated.array();
209
210   // just check if it has received at least it's bound
211   for (int p = 0; p < rho.size(); p++) {
212     if (double_equals(rho[p], idx2Var_.at(p)->get_bound(), sg_maxmin_precision)) {
213       player_max_share(0, p) = 1; // it doesn't really matter, just to say that it's a bmf
214       saturated[0]           = 1;
215     }
216   }
217
218   // 2) at least 1 resource is saturated
219   bmf = bmf && (saturated.array() == 1).any();
220
221   XBT_DEBUG("Player_ji usage of saturated resources:\n%s", debug_eigen(player_max_share).c_str());
222   // for all columns(players) it has to be the max at least in 1
223   bmf = bmf && (player_max_share.colwise().sum().all() >= 1);
224   return bmf;
225 }
226
227 void simgrid::kernel::lmm::BmfSystem::bottleneck_solve()
228 {
229   if (not modified_)
230     return;
231
232   XBT_DEBUG("");
233   XBT_DEBUG("Starting BMF solver");
234   /* initialize players' weight and constraint matrices */
235   set_vector_C();
236   set_matrix_A();
237   XBT_DEBUG("A:\n%s", debug_eigen(A_).c_str());
238   XBT_DEBUG("C:\n%s", debug_eigen(C_).c_str());
239
240   /* no flows to share, just returns */
241   if (A_.cols() == 0)
242     return;
243
244   int it            = 0;
245   auto fair_sharing = C_;
246
247   /* BMF allocation for each player (current and last one) stop when are equal */
248   std::unordered_map<int, std::vector<int>> last_alloc;
249   auto cur_alloc = get_alloc(fair_sharing, true);
250   Eigen::VectorXd rho;
251   while (it < max_iteration_ && last_alloc != cur_alloc) {
252     last_alloc = cur_alloc;
253     XBT_DEBUG("BMF: iteration %d", it);
254     XBT_DEBUG("B (current allocation): %s", debug_alloc(cur_alloc).c_str());
255
256     // solve inv(A)*rho = C
257     rho = equilibrium(cur_alloc);
258     XBT_DEBUG("rho:\n%s", debug_eigen(rho).c_str());
259
260     // get fair sharing for each resource
261     set_fair_sharing(cur_alloc, rho, fair_sharing);
262     XBT_DEBUG("Fair sharing vector (per resource):\n%s", debug_eigen(fair_sharing).c_str());
263
264     // get new allocation for players
265     cur_alloc = get_alloc(fair_sharing, false);
266     XBT_DEBUG("B (new allocation): %s", debug_alloc(cur_alloc).c_str());
267     it++;
268   }
269
270   xbt_assert(is_bmf(rho), "Not a BMF allocation");
271
272   /* setting rhos */
273   for (int i = 0; i < rho.size(); i++) {
274     idx2Var_[i]->value_ = rho[i];
275   }
276
277   XBT_DEBUG("BMF done after %d iterations", it);
278   print();
279 }