Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
further refacto smpi_factors to reduce dupplication
[simgrid.git] / src / smpi / internals / smpi_utils.cpp
1 /* Copyright (c) 2016-2022. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include "smpi_utils.hpp"
8
9 #include "private.hpp"
10 #include "smpi_config.hpp"
11 #include "src/surf/xml/platf.hpp"
12 #include "xbt/file.hpp"
13 #include "xbt/log.h"
14 #include "xbt/ex.h"
15 #include "xbt/parse_units.hpp"
16 #include "xbt/sysdep.h"
17 #include <algorithm>
18 #include <boost/tokenizer.hpp>
19
20 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_utils, smpi, "Logging specific to SMPI (utils)");
21
22 extern std::string surf_parsed_filename;
23 extern int surf_parse_lineno;
24
25 namespace simgrid::smpi::utils {
26
27 double total_benched_time=0;
28 unsigned long total_malloc_size=0;
29 unsigned long total_shared_size=0;
30 unsigned int total_shared_calls=0;
31 struct alloc_metadata_t {
32   size_t size          = 0;
33   unsigned int numcall = 0;
34   int line             = 0;
35   std::string file;
36 };
37
38 struct current_buffer_metadata_t {
39   alloc_metadata_t alloc;
40   std::string name;
41 };
42
43 alloc_metadata_t max_malloc;
44 F2C* current_handle = nullptr;
45 current_buffer_metadata_t current_buffer1;
46 current_buffer_metadata_t current_buffer2;
47
48 std::unordered_map<const void*, alloc_metadata_t> allocs;
49
50 std::unordered_map<int, std::vector<std::string>> collective_calls;
51
52 void FactorSet::parse(const std::string& values)
53 {
54   factors_     = parse_factor(values);
55   initialized_ = true;
56 }
57
58 FactorSet::FactorSet(const std::string& name, double default_value,
59                      std::function<double(s_smpi_factor_t const&, double)> const& lambda)
60     : name_(name), default_value_(default_value), lambda_(lambda)
61 {
62 }
63
64 double FactorSet::operator()()
65 {
66   return lambda_(factors_.front(), 0);
67 }
68
69 double FactorSet::operator()(double size)
70 {
71   if (factors_.empty())
72     return default_value_;
73
74   for (long unsigned i = 0; i < factors_.size(); i++) {
75     auto const& fact = factors_[i];
76
77     if (size <= fact.factor) { // Too large already, use the previous value
78
79       if (i == 0) { // Before the first boundary: use the default value
80         XBT_DEBUG("%s: %f <= %zu return default %f", name_.c_str(), size, fact.factor, default_value_);
81         return default_value_;
82       }
83       double val = lambda_(factors_[i - 1], size);
84       XBT_DEBUG("%s: %f <= %zu return %f", name_.c_str(), size, fact.factor, val);
85       return val;
86     }
87   }
88   double val = lambda_(factors_.back(), size);
89
90   XBT_DEBUG("%s: %f > %zu return %f", name_.c_str(), size, factors_.back().factor, val);
91   return val;
92 }
93
94 std::vector<s_smpi_factor_t> parse_factor(const std::string& smpi_coef_string)
95 {
96   std::vector<s_smpi_factor_t> smpi_factor;
97
98   /** Setup the tokenizer that parses the string **/
99   using Tokenizer = boost::tokenizer<boost::char_separator<char>>;
100   boost::char_separator<char> sep(";");
101   boost::char_separator<char> factor_separator(":");
102   Tokenizer tokens(smpi_coef_string, sep);
103
104   /**
105    * Iterate over patterns like A:B:C:D;E:F;G:H
106    * These will be broken down into:
107    * A --> B, C, D
108    * E --> F
109    * G --> H
110    */
111   for (auto token_iter = tokens.begin(); token_iter != tokens.end(); ++token_iter) {
112     XBT_DEBUG("token: %s", token_iter->c_str());
113     Tokenizer factor_values(*token_iter, factor_separator);
114     s_smpi_factor_t fact;
115     xbt_assert(factor_values.begin() != factor_values.end(), "Malformed radical for smpi factor: '%s'",
116                smpi_coef_string.c_str());
117     unsigned int iteration = 0;
118     for (auto factor_iter = factor_values.begin(); factor_iter != factor_values.end(); ++factor_iter) {
119       iteration++;
120
121       if (factor_iter == factor_values.begin()) { /* first element */
122         try {
123           fact.factor = std::stoi(*factor_iter);
124         } catch (const std::invalid_argument&) {
125           throw std::invalid_argument(std::string("Invalid factor in chunk ") + std::to_string(smpi_factor.size() + 1) +
126                                       ": " + *factor_iter);
127         }
128       } else {
129         try {
130           fact.values.push_back(xbt_parse_get_time(surf_parsed_filename, surf_parse_lineno, *factor_iter, ""));
131         } catch (const std::invalid_argument&) {
132           throw std::invalid_argument(std::string("Invalid factor value ") + std::to_string(iteration) + " in chunk " +
133                                       std::to_string(smpi_factor.size() + 1) + ": " + *factor_iter);
134         }
135       }
136     }
137
138     smpi_factor.push_back(fact);
139     XBT_DEBUG("smpi_factor:\t%zu: %zu values, first: %f", fact.factor, smpi_factor.size(), fact.values[0]);
140   }
141   std::sort(smpi_factor.begin(), smpi_factor.end(), [](const s_smpi_factor_t &pa, const s_smpi_factor_t &pb) {
142     return (pa.factor < pb.factor);
143   });
144   for (auto const& fact : smpi_factor) {
145     XBT_DEBUG("smpi_factor:\t%zu: %zu values, first: %f", fact.factor, smpi_factor.size(), fact.values[0]);
146   }
147   smpi_factor.shrink_to_fit();
148
149   return smpi_factor;
150 }
151
152 void add_benched_time(double time){
153   total_benched_time += time;
154 }
155
156 void account_malloc_size(size_t size, std::string_view file, int line, const void* ptr)
157 {
158   if (smpi_cfg_display_alloc()) {
159     alloc_metadata_t metadata;
160     metadata.size = size;
161     metadata.line = line;
162     metadata.numcall = 1;
163     metadata.file    = file;
164     allocs.try_emplace(ptr, metadata);
165
166     total_malloc_size += size;
167     if(size > max_malloc.size){
168       max_malloc.size = size;
169       max_malloc.line = line;
170       max_malloc.numcall = 1;
171       max_malloc.file    = file;
172     } else if (size == max_malloc.size && max_malloc.line == line && max_malloc.file == file) {
173       max_malloc.numcall++;
174     }
175   }
176 }
177
178 void account_shared_size(size_t size){
179   if (smpi_cfg_display_alloc()) {
180     total_shared_size += size;
181     total_shared_calls++;
182   }
183 }
184
185 void print_time_analysis(double global_time){
186   if (simgrid::config::get_value<bool>("smpi/display-timing")) {
187     XBT_INFO("Simulated time: %g seconds. \n\n"
188              "The simulation took %g seconds (after parsing and platform setup)\n"
189              "%g seconds were actual computation of the application",
190              simgrid_get_clock(), global_time, total_benched_time);
191     if (total_benched_time/global_time>=0.75)
192       XBT_INFO("More than 75%% of the time was spent inside the application code.\n"
193     "You may want to use sampling functions or trace replay to reduce this.");
194   }
195 }
196
197 static void print_leaked_handles()
198 {
199   // Put the leaked non-default handles in a vector to sort them by id
200   std::vector<std::pair<unsigned int, smpi::F2C*>> handles;
201   if (simgrid::smpi::F2C::lookup() != nullptr)
202     std::copy_if(simgrid::smpi::F2C::lookup()->begin(), simgrid::smpi::F2C::lookup()->end(),
203                  std::back_inserter(handles),
204                  [](auto const& entry) { return entry.first >= simgrid::smpi::F2C::get_num_default_handles(); });
205   if (handles.empty())
206     return;
207
208   auto max            = static_cast<unsigned long>(simgrid::config::get_value<int>("smpi/list-leaks"));
209   std::string message = "Probable memory leaks in your code: SMPI detected %zu unfreed MPI handles:";
210   if (max == 0)
211     message += "\nHINT: Display types and addresses (n max) with --cfg=smpi/list-leaks:n.\n"
212                "Running smpirun with -wrapper \"valgrind --leak-check=full\" can provide more information";
213   XBT_INFO(message.c_str(), handles.size());
214   if (max == 0)
215     return;
216
217   // we cannot trust F2C::lookup()->size() > F2C::get_num_default_handles() because some default handles are already
218   // freed at this point
219   bool display_advice = false;
220   std::map<std::string, int, std::less<>> count;
221   for (const auto& [_, elem] : handles) {
222     std::string key = elem->name();
223     if ((not xbt_log_no_loc) && (not elem->call_location().empty()))
224       key += " at " + elem->call_location();
225     else
226       display_advice = true;
227     auto& result = count.try_emplace(key, 0).first->second;
228     result++;
229   }
230   if (display_advice)
231     XBT_WARN("To get more information (location of allocations), compile your code with -trace-call-location flag of "
232              "smpicc/f90");
233   unsigned int i = 0;
234   for (const auto& [key, value] : count) {
235     if (value == 1)
236       XBT_INFO("leaked handle of type %s", key.c_str());
237     else
238       XBT_INFO("%d leaked handles of type %s", value, key.c_str());
239     i++;
240     if (i == max)
241       break;
242   }
243   if (max < count.size())
244     XBT_INFO("(%lu more handle leaks hidden as you wanted to see only %lu of them)", count.size() - max, max);
245 }
246
247 static void print_leaked_buffers()
248 {
249   if (allocs.empty())
250     return;
251
252   auto max            = static_cast<unsigned long>(simgrid::config::get_value<int>("smpi/list-leaks"));
253   std::string message = "Probable memory leaks in your code: SMPI detected %zu unfreed buffers:";
254   if (max == 0)
255     message += "display types and addresses (n max) with --cfg=smpi/list-leaks:n.\nRunning smpirun with -wrapper "
256                "\"valgrind --leak-check=full\" can provide more information";
257   XBT_INFO(message.c_str(), allocs.size());
258
259   if (max == 0)
260     return;
261
262   // gather by allocation origin (only one group reported in case of no-loc or if trace-call-location is not used)
263   struct buff_leak {
264     int count;
265     size_t total_size;
266     size_t min_size;
267     size_t max_size;
268   };
269   std::map<std::string, struct buff_leak, std::less<>> leaks_aggreg;
270   for (const auto& [_, elem] : allocs) {
271     std::string key = "leaked allocations";
272     if (not xbt_log_no_loc)
273       key = elem.file + ":" + std::to_string(elem.line) + ": " + key;
274     auto& result = leaks_aggreg.try_emplace(key, buff_leak{0, 0, elem.size, elem.size}).first->second;
275     result.count++;
276     result.total_size += elem.size;
277     if (elem.size > result.max_size)
278       result.max_size = elem.size;
279     else if (elem.size < result.min_size)
280       result.min_size = elem.size;
281   }
282   // now we can order by total size.
283   std::vector<std::pair<std::string, buff_leak>> leaks(leaks_aggreg.begin(), leaks_aggreg.end());
284   std::sort(leaks.begin(), leaks.end(),
285             [](auto const& a, auto const& b) { return a.second.total_size > b.second.total_size; });
286
287   unsigned int i = 0;
288   for (const auto& [key, value] : leaks) {
289     if (value.min_size == value.max_size)
290       XBT_INFO("%s of total size %zu, called %d times, each with size %zu", key.c_str(), value.total_size, value.count,
291                value.min_size);
292     else
293       XBT_INFO("%s of total size %zu, called %d times, with minimum size %zu and maximum size %zu", key.c_str(),
294                value.total_size, value.count, value.min_size, value.max_size);
295     i++;
296     if (i == max)
297       break;
298   }
299   if (max < leaks_aggreg.size())
300     XBT_INFO("(more buffer leaks hidden as you wanted to see only %lu of them)", max);
301 }
302
303 void print_memory_analysis()
304 {
305   if (smpi_cfg_display_alloc()) {
306     print_leaked_handles();
307     print_leaked_buffers();
308
309     if(total_malloc_size != 0)
310       XBT_INFO("Memory Usage: Simulated application allocated %lu bytes during its lifetime through malloc/calloc calls.\n"
311              "Largest allocation at once from a single process was %zu bytes, at %s:%d. It was called %u times during the whole simulation.\n"
312              "If this is too much, consider sharing allocations for computation buffers.\n"
313              "This can be done automatically by setting --cfg=smpi/auto-shared-malloc-thresh to the minimum size wanted size (this can alter execution if data content is necessary)\n",
314              total_malloc_size, max_malloc.size, simgrid::xbt::Path(max_malloc.file).get_base_name().c_str(), max_malloc.line, max_malloc.numcall
315       );
316     else
317       XBT_INFO(
318           "Allocations analysis asked, but 0 bytes were allocated through malloc/calloc calls intercepted by SMPI.\n"
319           "The code may not use malloc() to allocate memory, or it was built with SMPI_NO_OVERRIDE_MALLOC");
320     if(total_shared_size != 0)
321       XBT_INFO("%lu bytes were automatically shared between processes, in %u calls\n", total_shared_size, total_shared_calls);
322   }
323 }
324
325 void set_current_handle(F2C* handle){
326   current_handle=handle;
327 }
328
329 void print_current_handle(){
330   if(current_handle){
331     if(current_handle->call_location().empty())
332       XBT_INFO("To get handle location information, pass -trace-call-location flag to smpicc/f90 as well");
333     else
334       XBT_INFO("Handle %s was allocated by a call at %s", current_handle->name().c_str(),
335                (char*)(current_handle->call_location().c_str()));
336   }
337 }
338
339 void set_current_buffer(int i, const char* name, const void* buf){
340   //clear previous one
341   if(i==1){
342     if(not current_buffer1.name.empty()){
343       current_buffer1.name="";
344     }
345     if(not current_buffer2.name.empty()){
346       current_buffer2.name="";
347     }
348   }
349   auto meta = allocs.find(buf);
350   if (meta == allocs.end()) {
351     XBT_DEBUG("Buffer %p was not allocated with malloc/calloc", buf);
352     return;
353   }
354   if(i==1){
355     current_buffer1.alloc = meta->second;
356     current_buffer1.name = name;
357   }else{
358     current_buffer2.alloc=meta->second;
359     current_buffer2.name=name;
360   }
361 }
362
363 void print_buffer_info()
364 {
365   if (not current_buffer1.name.empty())
366     XBT_INFO("Buffer %s was allocated from %s line %d, with size %zu", current_buffer1.name.c_str(),
367              current_buffer1.alloc.file.c_str(), current_buffer1.alloc.line, current_buffer1.alloc.size);
368   if (not current_buffer2.name.empty())
369     XBT_INFO("Buffer %s was allocated from %s line %d, with size %zu", current_buffer2.name.c_str(),
370              current_buffer2.alloc.file.c_str(), current_buffer2.alloc.line, current_buffer2.alloc.size);
371 }
372
373 size_t get_buffer_size(const void* buf){
374   auto meta = allocs.find(buf);
375   if (meta == allocs.end()) {
376     //we don't know this buffer (on stack or feature disabled), assume it's fine.
377     return  std::numeric_limits<std::size_t>::max();
378   }
379   return meta->second.size;
380 }
381
382 void account_free(const void* ptr){
383   if (smpi_cfg_display_alloc()) {
384     allocs.erase(ptr);
385   }
386 }
387
388 int check_collectives_ordering(MPI_Comm comm, const std::string& call)
389 {
390   unsigned int count = comm->get_collectives_count();
391   comm->increment_collectives_count();
392   if (auto vec = collective_calls.find(comm->id()); vec == collective_calls.end()) {
393     collective_calls.try_emplace(comm->id(), std::vector<std::string>{call});
394   } else {
395     // are we the first ? add the call
396     if (vec->second.size() == count) {
397       vec->second.emplace_back(call);
398     } else if (vec->second.size() > count) {
399       if (vec->second[count] != call) {
400         XBT_WARN("Collective operation mismatch. For process %ld, expected %s, got %s",
401                  simgrid::s4u::this_actor::get_pid(), vec->second[count].c_str(), call.c_str());
402         return MPI_ERR_OTHER;
403       }
404     } else {
405       THROW_IMPOSSIBLE;
406     }
407   }
408   return MPI_SUCCESS;
409 }
410 } // namespace simgrid::smpi::utils