Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of https://framagit.org/simgrid/simgrid
[simgrid.git] / src / kernel / lmm / bmf.hpp
1 /* Copyright (c) 2004-2023. 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 #ifndef SIMGRID_KERNEL_LMM_BMF_HPP
7 #define SIMGRID_KERNEL_LMM_BMF_HPP
8
9 #include "src/kernel/lmm/System.hpp"
10 #include "xbt/config.hpp"
11
12 #include <set>
13
14 #ifdef __clang__
15 // Ignore deprecation warnings with Eigen < 4.0 (see https://gitlab.com/libeigen/eigen/-/issues/1850)
16 #pragma clang diagnostic push
17 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
18 #endif
19 #include <Eigen/Dense>
20 #ifdef __clang__
21 #pragma clang diagnostic pop
22 #endif
23
24 #include <unordered_set>
25
26 namespace simgrid::kernel::lmm {
27
28 /** @brief Generate all combinations of valid allocation */
29 class XBT_PUBLIC AllocationGenerator {
30 public:
31   explicit AllocationGenerator(Eigen::MatrixXd A);
32
33   /**
34    * @brief Get next valid allocation
35    *
36    * @param next_alloc Allocation (OUTPUT)
37    * @return true if there's an allocation not tested yet, false otherwise
38    */
39   bool next(std::vector<int>& next_alloc);
40
41 private:
42   Eigen::MatrixXd A_;
43   std::vector<int> alloc_;
44   bool first_ = true;
45 };
46
47 /**
48  * @beginrst
49  *
50  * Despite the simplicity of BMF fairness definition, it's quite hard to
51  * find a BMF allocation in the general case.
52  *
53  * This solver implements one possible algorithm to find a BMF, as proposed
54  * at: https://hal.archives-ouvertes.fr/hal-01552739.
55  *
56  * The idea of this algorithm is that each player/flow "selects" a resource to
57  * saturate. Then, we calculate the rate each flow would have with this allocation.
58  * If the allocation is a valid BMF and no one needs to move, it's over. Otherwise,
59  * each player selects a new resource to saturate based on the minimim rate possible
60  * between all resources.
61  *
62  * The steps:
63  * 1) Given an initial allocation B_i
64  * 2) Build a matrix A'_ji and C'_ji which assures that the player receives the most
65  * share at selected resources
66  * 3) Solve: A'_ji * rho_i = C'_j
67  * 4) Calculate the minimum fair rate for each resource j: f_j. The f_j represents
68  * the maximum each flow can receive at the resource j.
69  * 5) Builds a new vector B'_i = arg min(f_j/A_ji).
70  * 6) Stop if B == B' (nobody needs to move), go to step 2 otherwise
71  *
72  * Despite the overall good performance of this algorithm, which converges in a few
73  * iterations, we don't have any assurance about its convergence. In the worst case,
74  * it may be needed to test all possible combination of allocations (which is exponential).
75  *
76  * @endrst
77  */
78 class XBT_PUBLIC BmfSolver {
79   inline static simgrid::config::Flag<int> cfg_bmf_max_iteration{
80       "bmf/max-iterations", "Maximum number of steps to be performed while searching for a BMF allocation", 1000};
81
82   inline static simgrid::config::Flag<double> cfg_bmf_precision{
83       "bmf/precision", {"precision/bmf"}, "Numerical precision used when computing resource sharing", 1E-12};
84
85 public:
86   /**
87    * @brief Instantiate the BMF solver
88    *
89    * @param A A_ji: consumption of player i on resource j
90    * @param maxA maxA_ji: consumption of larger player i on resource j
91    * @param C Resource capacity
92    * @param shared Is resource shared between player or each player receives the full capacity (FATPIPE links)
93    * @param phi Bound for each player
94    */
95   BmfSolver(Eigen::MatrixXd A, Eigen::MatrixXd maxA, Eigen::VectorXd C, std::vector<bool> shared, Eigen::VectorXd phi);
96   /** @brief Solve equation system to find a fair-sharing of resources */
97   Eigen::VectorXd solve();
98
99 private:
100   using allocation_map_t = std::unordered_map<int, std::unordered_set<int>>;
101   /**
102    * @brief Get actual resource capacity considering bounded players
103    *
104    * Calculates the resource capacity considering that some players on it may be bounded by user,
105    * i.e. an explicit limit in speed was configured
106    *
107    * @param resource Internal index of resource in C_ vector
108    * @param bounded_players List of players that are externally bounded
109    * @return Actual resource capacity
110    */
111   double get_resource_capacity(int resource, const std::vector<int>& bounded_players) const;
112   /**
113    * @brief Get maxmin share of the resource
114    *
115    * @param resource Internal index of resource in C_ vector
116    * @param bounded_players List of players that are externally bounded
117    * @return maxmin share
118    */
119   double get_maxmin_share(int resource, const std::vector<int>& bounded_players) const;
120   /**
121    * @brief Auxiliary method to get list of bounded player from allocation
122    *
123    * @param alloc Current allocation
124    * @return list of bounded players
125    */
126   std::vector<int> get_bounded_players(const allocation_map_t& alloc) const;
127
128   /**
129    * @brief Given an allocation calculates the speed/rho for each player
130    *
131    * Do the magic!!
132    * Builds 2 auxiliares matrices A' and C' and solves the system: rho_i = inv(A'_ji) * C'_j
133    *
134    * All resources in A' and C' are saturated, i.e., sum(A'_j * rho_i) = C'_j.
135    *
136    * The matrix A' is built as follows:
137    * - For each resource j in alloc: copy row A_j to A'
138    * - If 2 players (i, k) share a same resource, assure fairness by adding a row in A' such as:
139    *   -  A_ji*rho_i - Ajk*rho_j = 0
140    *
141    * @param alloc for each resource, players that chose to saturate it
142    * @return Vector rho with "players' speed"
143    */
144   Eigen::VectorXd equilibrium(const allocation_map_t& alloc) const;
145
146   /**
147    * @brief Given a fair_sharing vector, gets the allocation
148    *
149    * The allocation for player i is given by: min(bound, f_j/A_ji).
150    * The minimum between all fair-sharing and the external bound (if any)
151    *
152    * The algorithm dictates a random initial allocation. For simplicity, we opt to use the same
153    * logic with the fair_sharing vector.
154    *
155    * @param fair_sharing Fair sharing vector
156    * @param initial Is this the initial allocation?
157    * @return allocation vector
158    */
159   bool get_alloc(const Eigen::VectorXd& fair_sharing, const allocation_map_t& last_alloc, allocation_map_t& alloc,
160                  bool initial);
161
162   bool disturb_allocation(allocation_map_t& alloc, std::vector<int>& alloc_by_player);
163   /**
164    * @brief Calculates the fair sharing for each resource
165    *
166    * Basically 3 options:
167    * 1) resource in allocation: A_ji*rho_i since all players who selected this resource have the same share
168    * 2) resource not selected by saturated (fully used): divide it by the number of players C_/n_players
169    * 3) resource not selected and not-saturated: no limitation
170    *
171    * @param alloc Allocation map (resource-> players)
172    * @param rho Speed for each player i
173    * @param fair_sharing Output vector, fair sharing for each resource j
174    */
175   void set_fair_sharing(const allocation_map_t& alloc, const Eigen::VectorXd& rho, Eigen::VectorXd& fair_sharing) const;
176
177   /**
178    * @brief Check if allocation is BMF
179    *
180    * To be a bmf allocation it must:
181    * - respect the capacity of all resources
182    * - saturate at least 1 resource
183    * - every player receives maximum share in at least 1 saturated resource
184    * @param rho Allocation
185    * @return true if BMF false otherwise
186    */
187   bool is_bmf(const Eigen::VectorXd& rho) const;
188   std::vector<int> alloc_map_to_vector(const allocation_map_t& alloc) const;
189
190   /**
191    * @brief Set of debug functions to print the different objects
192    */
193   template <typename T> std::string debug_eigen(const T& obj) const;
194   template <typename C> std::string debug_vector(const C& container) const;
195   std::string debug_alloc(const allocation_map_t& alloc) const;
196
197   Eigen::MatrixXd A_;    //!< A_ji: resource usage matrix, each row j represents a resource and col i a flow/player
198   Eigen::MatrixXd maxA_; //!< maxA_ji,  similar as A_, but containing the maximum consumption of player i (if player a
199                          //!< single flow it's equal to A_)
200   Eigen::VectorXd C_;    //!< C_j Capacity of each resource
201   std::vector<bool> C_shared_; //!< shared_j Resource j is shared or not
202   Eigen::VectorXd phi_;        //!< phi_i bound for each player
203
204   std::set<std::vector<int>> allocations_; //!< set of already tested allocations, since last identified loop
205   AllocationGenerator gen_;
206   static constexpr int NO_RESOURCE = -1;                    //!< flag to indicate player has selected no resource
207   int max_iteration_               = cfg_bmf_max_iteration; //!< number maximum of iterations of BMF algorithm
208 };
209
210 /**
211  * @beginrst
212  *
213  * A BMF (bottleneck max fairness) solver to resolve inequation systems.
214  *
215  * Usually, SimGrid relies on a *max-min fairness* solver to share the resources.
216  * Max-min is great when sharing homogenous resources, however it cannot be used with heterogeneous resources.
217  *
218  * BMF is a natural alternative to max-min, providing a fair-sharing of heterogeneous resources (CPU, network, disk).
219  * It is specially relevant for the implementation of parallel tasks whose sharing involves different
220  * kinds of resources.
221  *
222  * BMF assures that every flow receives the maximum share possible in at least 1 bottleneck (fully used) resource.
223  *
224  * The BMF is characterized by:
225  * - A_ji: a matrix of requirement for flows/player. For each resource j, and flow i, A_ji represents the utilization
226  * of resource j for 1 unit of the flow i.
227  * - rho_i: the rate allocated for flow i (same among all resources)
228  * - C_j: the capacity of each resource (can be bytes/s, flops/s, etc)
229  *
230  * Therefore, these conditions need to satisfied to an allocation be considered a BMF:
231  * 1) All constraints are respected (flows cannot use more than the resource has available)
232  *   - for all resource j and player i: A_ji * rho_i <= C_j
233  * 2) At least 1 resource is fully used (bottleneck).
234  *   - for some resource j: A_ji * rho_i = C_j
235  * 3) Each flow (player) receives the maximum share in at least 1 bottleneck.
236  *   - for all player i: exist a resource j: A_ji * rho_i >= A_jk * rho_k for all other player k
237  *
238  * Despite the prove of existence of a BMF allocation in the general case, it may not
239  * be unique, which leads to possible different rate for the applications.
240  *
241  * More details about BMF can be found at: https://hal.inria.fr/hal-01243985/document
242  *
243  * @endrst
244  */
245 /**
246  * @brief Bottleneck max-fair system
247  */
248 class XBT_PUBLIC BmfSystem : public System {
249 public:
250   using System::System;
251
252 private:
253   /** @brief Implements the solve method to calculate a BMF allocation */
254   void do_solve() final;
255   using allocation_map_t = std::unordered_map<int, std::unordered_set<int>>;
256   /**
257    * @brief Solve equation system to find a fair-sharing of resources
258    *
259    * @param cnst_list Constraint list (modified for selective update or active)
260    */
261   template <class CnstList> void bmf_solve(const CnstList& cnst_list);
262   /**
263    * @brief Iterates over system and build the consumption matrix A_ji and maxA_ji
264    *
265    * Each row j represents a resource and each col i a player/flow
266    *
267    * Considers only active variables to build the matrix.
268    *
269    * @param number_cnsts Number of constraints in the system
270    * @param A Consumption matrix (OUTPUT)
271    * @param maxA Max subflow consumption matrix (OUTPUT)
272    * @param phi Bounds for variables
273    */
274   void get_flows_data(Eigen::Index number_cnsts, Eigen::MatrixXd& A, Eigen::MatrixXd& maxA, Eigen::VectorXd& phi);
275   /**
276    * @brief Builds the vector C_ with resource's capacity
277    *
278    * @param cnst_list Constraint list (modified for selective update or active)
279    * @param C Resource capacity vector
280    * @param shared Resource is shared or not (fatpipe links)
281    */
282   template <class CnstList>
283   void get_constraint_data(const CnstList& cnst_list, Eigen::VectorXd& C, std::vector<bool>& shared);
284
285   std::unordered_map<int, Variable*> idx2Var_; //!< Map player index (and position in matrices) to system's variable
286   std::unordered_map<const Constraint*, int> cnst2idx_; //!< Conversely map constraint to index
287 };
288
289 } // namespace simgrid::kernel::lmm
290
291 #endif