Debian Codegraph @

packages/seacas/libraries/ioss/src/Ioss_DecompositionUtils.C

raw
1 /*
2 * Copyright(C) 2024 National Technology & Engineering Solutions
3 * of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
4 * NTESS, the U.S. Government retains certain rights in this software.
5 *
6 * See packages/seacas/LICENSE for details
7 */
8
9 #include <map>
10 #include <numeric>
11 #include <string>
12 #include <vector>
13
14 #include "Ioss_ChainGenerator.h"
15 #include "Ioss_CodeTypes.h"
16 #include "Ioss_DecompositionUtils.h"
17 #include "Ioss_ElementBlock.h"
18 #include "Ioss_NodeBlock.h"
19 #include "Ioss_ParallelUtils.h"
20 #include "Ioss_Region.h"
21 #include "Ioss_SmartAssert.h"
22
23 #include <fmt/color.h>
24 #include <fmt/format.h>
25 #include <fmt/ostream.h>
26 #include <fmt/ranges.h>
27
28 #if !defined(NO_ZOLTAN_SUPPORT)
29 #include <zoltan.h> // for Zoltan_Initialize
30 #include <zoltan_cpp.h> // for Zoltan
31 #endif
32
33 namespace {
34 #if !defined(NO_ZOLTAN_SUPPORT)
35 /*****************************************************************************/
36 /***** Global data structure used by Zoltan callbacks. *****/
37 /***** Could implement Zoltan callbacks without global data structure, *****/
38 /***** but using the global data structure makes implementation quick. *****/
39 struct
40 {
41 size_t ndot; /* Length of x, y, z, and part (== # of elements) */
42 float *vwgt; /* vertex weights */
43 double *x; /* x-coordinates */
44 double *y; /* y-coordinates */
45 double *z; /* z-coordinates */
46 } Zoltan_Data;
47
48 /*****************************************************************************/
49 /***** ZOLTAN CALLBACK FUNCTIONS *****/
50 int zoltan_num_dim(void * /*data*/, int *ierr)
51 {
52 /* Return dimensionality of coordinate data.
53 * Using global data structure Zoltan_Data, initialized in ZOLTAN_RCB_assign.
54 */
55 *ierr = ZOLTAN_OK;
56 if (Zoltan_Data.z != nullptr) {
57 return 3;
58 }
59 if (Zoltan_Data.y != nullptr) {
60 return 2;
61 }
62 return 1;
63 }
64
65 int zoltan_num_obj(void * /*data*/, int *ierr)
66 {
67 /* Return number of objects.
68 * Using global data structure Zoltan_Data, initialized in ZOLTAN_RCB_assign.
69 */
70 *ierr = ZOLTAN_OK;
71 return Zoltan_Data.ndot;
72 }
73
74 void zoltan_obj_list(void * /*data*/, int /*ngid_ent*/, int /*nlid_ent*/, ZOLTAN_ID_PTR gids,
75 ZOLTAN_ID_PTR /*lids*/, int wdim, float *wgts, int *ierr)
76 {
77 /* Return list of object IDs.
78 * Return only global IDs; don't need local IDs since running in serial.
79 * gids are array indices for coordinate and vwgts arrays.
80 * Using global data structure Zoltan_Data, initialized in ZOLTAN_RCB_assign.
81 */
82 std::iota(gids, gids + Zoltan_Data.ndot, 0);
83 if (wdim != 0) {
84 for (size_t i = 0; i < Zoltan_Data.ndot; i++) {
85 wgts[i] = static_cast<float>(Zoltan_Data.vwgt[i]);
86 }
87 }
88
89 *ierr = ZOLTAN_OK;
90 }
91
92 void zoltan_geom(void * /*data*/, int /*ngid_ent*/, int /*nlid_ent*/, int nobj,
93 const ZOLTAN_ID_PTR gids, ZOLTAN_ID_PTR /*lids*/, int ndim, double *geom,
94 int *ierr)
95 {
96 /* Return coordinates for objects.
97 * gids are array indices for coordinate arrays.
98 * Using global data structure Zoltan_Data, initialized in ZOLTAN_RCB_assign.
99 */
100
101 for (size_t i = 0; i < static_cast<size_t>(nobj); i++) {
102 size_t j = gids[i];
103 geom[i * ndim] = Zoltan_Data.x[j];
104 if (ndim > 1) {
105 geom[i * ndim + 1] = Zoltan_Data.y[j];
106 }
107 if (ndim > 2) {
108 geom[i * ndim + 2] = Zoltan_Data.z[j];
109 }
110 }
111
112 *ierr = ZOLTAN_OK;
113 }
114 #endif
115
116 template <typename INT>
117 std::map<INT, std::vector<INT>> string_chains(const Ioss::chain_t<INT> &element_chains)
118 {
119 std::map<INT, std::vector<INT>> chains;
120
121 for (size_t i = 0; i < element_chains.size(); i++) {
122 auto &chain_entry = element_chains[i];
123 if (chain_entry.link >= 0) {
124 chains[chain_entry.element].push_back(i + 1);
125 }
126 }
127 return chains;
128 }
129 } // namespace
130
131 namespace Ioss {
132 void DecompUtils::output_histogram(const std::vector<size_t> &proc_work, double avg_work,
133 size_t median)
134 {
135 fmt::print("Work-per-processor Histogram:\n");
136 std::array<size_t, 16> histogram{};
137
138 auto wmin = *std::min_element(proc_work.begin(), proc_work.end());
139 auto wmax = *std::max_element(proc_work.begin(), proc_work.end());
140
141 size_t hist_size = std::min(size_t(16), (wmax - wmin));
142 hist_size = std::min(hist_size, proc_work.size());
143
144 if (hist_size <= 1) {
145 fmt::print("\tWork is the same on all processors; no histogram needed.\n\n");
146 return;
147 }
148
149 auto delta = double(wmax + 1 - wmin) / hist_size;
150 for (const auto &pw : proc_work) {
151 auto bin = size_t(double(pw - wmin) / delta);
152 SMART_ASSERT(bin < hist_size)(bin)(hist_size);
153 histogram[bin]++;
154 }
155
156 size_t proc_width = Ioss::Utils::number_width(proc_work.size(), true);
157 size_t work_width = Ioss::Utils::number_width(wmax, true);
158
159 fmt::print("\n\t{:^{}} {:^{}}\n", "Work Range", 2 * work_width + 2, "#", proc_width);
160 auto hist_max = *std::max_element(histogram.begin(), histogram.end());
161 for (size_t i = 0; i < hist_size; i++) {
162 int max_star = 50;
163 int star_cnt = ((double)histogram[i] / hist_max * max_star);
164 std::string stars(star_cnt, '*');
165 for (int j = 9; j < star_cnt;) {
166 stars[j] = '|';
167 j += 10;
168 }
169 if (histogram[i] > 0 && star_cnt == 0) {
170 stars = '.';
171 }
172 size_t w1 = wmin + size_t(i * delta);
173 size_t w2 = wmin + size_t((i + 1) * delta);
174 std::string postfix;
175 if (w1 <= avg_work && avg_work < w2) {
176 postfix += "average";
177 }
178 if (w1 <= median && median < w2) {
179 if (!postfix.empty()) {
180 postfix += ", ";
181 }
182 postfix += "median";
183 }
184 fmt::print("\t{:{}}..{:{}} ({:{}}):\t{:{}} {}\n", fmt::group_digits(w1), work_width,
185 fmt::group_digits(w2), work_width, fmt::group_digits(histogram[i]), proc_width,
186 stars, max_star, postfix);
187 }
188 fmt::print("\n");
189 }
190
191 template IOSS_EXPORT void
192 DecompUtils::decompose_zoltan(const Ioss::Region &region, int ranks, const std::string &method,
193 std::vector<int> &elem_to_proc, const std::vector<float> &weights,
194 bool ignore_x, bool ignore_y, bool ignore_z,
195 IOSS_MAYBE_UNUSED int dummy);
196 template IOSS_EXPORT void
197 DecompUtils::decompose_zoltan(const Ioss::Region &region, int ranks, const std::string &method,
198 std::vector<int> &elem_to_proc, const std::vector<float> &weights,
199 bool ignore_x, bool ignore_y, bool ignore_z,
200 IOSS_MAYBE_UNUSED int64_t dummy);
201
202 template <typename INT>
203 void DecompUtils::decompose_zoltan(const Ioss::Region &region, int ranks,
204 const std::string &method, std::vector<int> &elem_to_proc,
205 const std::vector<float> &weights, bool ignore_x,
206 bool ignore_y, bool ignore_z, IOSS_MAYBE_UNUSED INT dummy)
207 {
208 #if defined(NO_ZOLTAN_SUPPORT)
209 fmt::print(stderr, "ERROR: Zoltan library not enabled in this version of slice.\n"
210 " The 'rcb', 'rib', and 'hsfc' methods are not available.\n\n");
211 std::exit(1);
212 #else
213 if (ranks == 1) {
214 return;
215 }
216
217 size_t element_count = region.get_property("element_count").get_int();
218 if (element_count != static_cast<size_t>(static_cast<int>(element_count))) {
219 fmt::print(stderr, "ERROR: Cannot have a mesh with more than 2.1 Billion elements in a "
220 "Zoltan decomposition.\n");
221 exit(EXIT_FAILURE);
222 }
223
224 auto [x, y, z] = Ioss::DecompUtils::get_element_centroid(region, dummy);
225
226 // Copy mesh data and pointers into structure accessible from callback fns.
227 Zoltan_Data.ndot = element_count;
228 Zoltan_Data.vwgt = const_cast<float *>(Data(weights));
229
230 if (ignore_x && ignore_y) {
231 x.clear();
232 y.clear();
233 Zoltan_Data.x = Data(z);
234 }
235 else if (ignore_x && ignore_z) {
236 x.clear();
237 z.clear();
238 Zoltan_Data.x = Data(y);
239 }
240 else if (ignore_y && ignore_z) {
241 y.clear();
242 z.clear();
243 Zoltan_Data.x = Data(x);
244 }
245 else if (ignore_x) {
246 x.clear();
247 Zoltan_Data.x = Data(y);
248 Zoltan_Data.y = Data(z);
249 }
250 else if (ignore_y) {
251 y.clear();
252 Zoltan_Data.x = Data(x);
253 Zoltan_Data.y = Data(z);
254 }
255 else if (ignore_z) {
256 z.clear();
257 Zoltan_Data.x = Data(x);
258 Zoltan_Data.y = Data(y);
259 }
260 else {
261 Zoltan_Data.x = Data(x);
262 Zoltan_Data.y = Data(y);
263 Zoltan_Data.z = Data(z);
264 }
265
266 // Initialize Zoltan
267 int argc = 0;
268 char **argv = nullptr;
269
270 float ver = 0.0;
271 Zoltan_Initialize(argc, argv, &ver);
272 fmt::print("\tUsing Zoltan version {:.2}, method {}\n", static_cast<double>(ver), method);
273
274 Zoltan zz(Ioss::ParallelUtils::comm_self());
275
276 // Register Callback functions
277 // Using global Zoltan_Data; could register it here instead as data field.
278 zz.Set_Num_Obj_Fn(zoltan_num_obj, nullptr);
279 zz.Set_Obj_List_Fn(zoltan_obj_list, nullptr);
280 zz.Set_Num_Geom_Fn(zoltan_num_dim, nullptr);
281 zz.Set_Geom_Multi_Fn(zoltan_geom, nullptr);
282
283 // Set parameters for Zoltan
284 zz.Set_Param("DEBUG_LEVEL", "0");
285 std::string str = fmt::format("{}", ranks);
286 zz.Set_Param("NUM_GLOBAL_PARTS", str);
287 zz.Set_Param("OBJ_WEIGHT_DIM", "1");
288 zz.Set_Param("LB_METHOD", method);
289 zz.Set_Param("NUM_LID_ENTRIES", "0");
290 zz.Set_Param("REMAP", "0");
291 zz.Set_Param("RETURN_LISTS", "PARTITION_ASSIGNMENTS");
292 zz.Set_Param("RCB_RECTILINEAR_BLOCKS", "1");
293
294 int num_global = sizeof(INT) / sizeof(ZOLTAN_ID_TYPE);
295 num_global = num_global < 1 ? 1 : num_global;
296
297 // Call partitioner
298 int changes = 0;
299 int num_local = 0;
300 int num_import = 1;
301 int num_export = 1;
302 ZOLTAN_ID_PTR import_global_ids = nullptr;
303 ZOLTAN_ID_PTR import_local_ids = nullptr;
304 ZOLTAN_ID_PTR export_global_ids = nullptr;
305 ZOLTAN_ID_PTR export_local_ids = nullptr;
306 int *import_procs = nullptr;
307 int *import_to_part = nullptr;
308 int *export_procs = nullptr;
309 int *export_to_part = nullptr;
310 int rc = zz.LB_Partition(changes, num_global, num_local, num_import, import_global_ids,
311 import_local_ids, import_procs, import_to_part, num_export,
312 export_global_ids, export_local_ids, export_procs, export_to_part);
313
314 if (rc != ZOLTAN_OK) {
315 fmt::print(stderr, "ERROR: Problem during call to Zoltan LB_Partition.\n");
316 goto End;
317 }
318
319 // Sanity check
320 if (element_count != static_cast<size_t>(num_export)) {
321 fmt::print(stderr, "Sanity check failed; ndot {} != num_export {}.\n", element_count,
322 static_cast<size_t>(num_export));
323 goto End;
324 }
325
326 elem_to_proc.resize(element_count);
327 for (size_t i = 0; i < element_count; i++) {
328 elem_to_proc[i] = export_to_part[i];
329 }
330
331 End:
332 /* Clean up */
333 Zoltan::LB_Free_Part(&import_global_ids, &import_local_ids, &import_procs, &import_to_part);
334 Zoltan::LB_Free_Part(&export_global_ids, &export_local_ids, &export_procs, &export_to_part);
335 #endif
336 }
337
338 template <typename INT>
339 void DecompUtils::line_decompose(Region &region, size_t num_ranks, const std::string &method,
340 const std::string &surface_list,
341 std::vector<int> &element_to_proc, INT dummy)
342 {
343
344 Ioss::chain_t<INT> element_chains =
345 Ioss::generate_element_chains(region, surface_list, 0, dummy);
346 region.get_database()->progress("Ioss::generate_element_chains");
347
348 std::vector<float> weights =
349 line_decomp_weights(element_chains, region.get_property("element_count").get_int());
350 region.get_database()->progress("generate_element_weights");
351
352 double start = Ioss::Utils::timer();
353 decompose_zoltan(region, num_ranks, method, element_to_proc, weights, false, false, false,
354 dummy);
355 double end = Ioss::Utils::timer();
356 fmt::print(stderr, "\tDecompose elements = {:.5}\n", end - start);
357 region.get_database()->progress("exit decompose_elements");
358
359 // Make sure all elements on a chain are on the same processor rank...
360 line_decomp_modify(element_chains, element_to_proc, num_ranks);
361 }
362
363 template IOSS_EXPORT void DecompUtils::line_decompose(Region &region, size_t num_ranks,
364 const std::string &method,
365 const std::string &surface_list,
366 std::vector<int> &element_to_proc,
367 int dummy);
368 template IOSS_EXPORT void DecompUtils::line_decompose(Region &region, size_t num_ranks,
369 const std::string &method,
370 const std::string &surface_list,
371 std::vector<int> &element_to_proc,
372 int64_t dummy);
373
374 template <typename INT>
375 std::vector<float> DecompUtils::line_decomp_weights(const Ioss::chain_t<INT> &element_chains,
376 size_t element_count)
377 {
378 int debug_level = 0;
379 auto chains = string_chains(element_chains);
380
381 if ((debug_level & 16) != 0) {
382 for (const auto &[chain_root, chain_elements] : chains) {
383 fmt::print("Chain Root: {} contains: {}\n", chain_root, fmt::join(chain_elements, ", "));
384 }
385 }
386
387 std::vector<float> weights(element_count, 1);
388 // Now, for each chain...
389 for (const auto &[chain_root, chain_elements] : chains) {
390 // * Set the weights of all elements in the chain...
391 // * non-root = 0, root = length of chain.
392 for (const auto &element : chain_elements) {
393 weights[element - 1] = 0;
394 }
395 weights[chain_root - 1] = static_cast<float>(chain_elements.size());
396 }
397 return weights;
398 }
399 template IOSS_EXPORT std::vector<float>
400 DecompUtils::line_decomp_weights(const Ioss::chain_t<int> &element_chains, size_t element_count);
401 template IOSS_EXPORT std::vector<float>
402 DecompUtils::line_decomp_weights(const Ioss::chain_t<int64_t> &element_chains,
403 size_t element_count);
404
405 template <typename INT>
406 void DecompUtils::line_decomp_modify(const Ioss::chain_t<INT> &element_chains,
407 std::vector<int> &elem_to_proc, int proc_count)
408 {
409 int debug_level = 0;
410 // Get a map of all chains and the elements in the chains. Map key will be root.
411 auto chains = string_chains(element_chains);
412
413 // Delta: elements added/removed from each processor...
414 std::vector<int> delta(proc_count);
415
416 // Now, for each chain...
417 for (const auto &[chain_root, chain_elements] : chains) {
418 if ((debug_level & 16) != 0) {
419 fmt::print("Chain Root: {} contains: {}\n", chain_root, fmt::join(chain_elements, ", "));
420 }
421
422 std::vector<INT> chain_proc_count(proc_count);
423
424 // * get processors used by elements in the chain...
425 for (const auto &element : chain_elements) {
426 auto proc = elem_to_proc[element - 1];
427 chain_proc_count[proc]++;
428 }
429
430 // * Now, subtract the `delta` from each count
431 for (int i = 0; i < proc_count; i++) {
432 chain_proc_count[i] -= delta[i];
433 }
434
435 // * Assign all elements in the chain to processor at chain root
436 // * Update the deltas for all processors that gain/lose elements...
437 auto root_proc = elem_to_proc[chain_root - 1];
438 for (const auto &element : chain_elements) {
439 if (elem_to_proc[element - 1] != root_proc) {
440 auto old_proc = elem_to_proc[element - 1];
441 elem_to_proc[element - 1] = root_proc;
442 delta[root_proc]++;
443 delta[old_proc]--;
444 }
445 }
446 }
447
448 std::vector<INT> proc_element_count(proc_count);
449 for (auto proc : elem_to_proc) {
450 proc_element_count[proc]++;
451 }
452 if ((debug_level & 32) != 0) {
453 fmt::print("\nElements/Processor: {}\n", fmt::join(proc_element_count, ", "));
454 fmt::print("Delta/Processor: {}\n", fmt::join(delta, ", "));
455 }
456 }
457
458 template IOSS_EXPORT void
459 DecompUtils::line_decomp_modify(const Ioss::chain_t<int> &element_chains,
460 std::vector<int> &elem_to_proc, int proc_count);
461 template IOSS_EXPORT void
462 DecompUtils::line_decomp_modify(const Ioss::chain_t<int64_t> &element_chains,
463 std::vector<int> &elem_to_proc, int proc_count);
464
465 std::vector<size_t> DecompUtils::get_work_per_rank(const std::vector<int> &elem_to_proc,
466 int proc_count)
467 {
468 std::vector<size_t> work_per_rank(proc_count);
469 for (int proc : elem_to_proc) {
470 work_per_rank[proc]++;
471 }
472 return work_per_rank;
473 }
474
475 std::pair<double, size_t>
476 DecompUtils::output_decomposition_statistics(const std::vector<size_t> work_per_rank)
477 {
478 size_t total_work = std::accumulate(work_per_rank.begin(), work_per_rank.end(), size_t(0));
479 size_t proc_count = work_per_rank.size();
480 size_t proc_width = Ioss::Utils::number_width(proc_count, false);
481 size_t work_width = Ioss::Utils::number_width(total_work, true);
482
483 auto min_work = *std::min_element(work_per_rank.begin(), work_per_rank.end());
484 auto max_work = *std::max_element(work_per_rank.begin(), work_per_rank.end());
485 double avg_work = 0.0;
486 size_t median = 0;
487 {
488 auto pw_copy(work_per_rank);
489 std::nth_element(pw_copy.begin(), pw_copy.begin() + pw_copy.size() / 2, pw_copy.end());
490 median = pw_copy[pw_copy.size() / 2];
491 fmt::print("\nWork per processor:\n\tMinimum = {}, Maximum = {}, Median = {}, Ratio = "
492 "{:.3}\n\n",
493 fmt::group_digits(min_work), fmt::group_digits(max_work),
494 fmt::group_digits(median), (double)(max_work) / min_work);
495 }
496 if (min_work == max_work) {
497 fmt::print("Work on all processors is {}\n\n", fmt::group_digits(min_work));
498 }
499 else {
500 int max_star = 40;
501 int min_star = max_star * ((double)min_work / (double)(max_work));
502 min_star = std::max(1, min_star);
503 int delta = max_star - min_star;
504
505 avg_work = (double)total_work / (double)proc_count;
506 for (size_t i = 0; i < work_per_rank.size(); i++) {
507 int star_cnt =
508 (double)(work_per_rank[i] - min_work) / (max_work - min_work) * delta + min_star;
509 std::string stars(star_cnt, '*');
510 auto tmp = fmt::format(fmt::runtime("\tProcessor {:{}}, work = {:{}} ({:.2f})\t{}\n"), i,
511 proc_width, fmt::group_digits(work_per_rank[i]), work_width,
512 work_per_rank[i] / avg_work, stars);
513
514 #if !defined __NVCC__
515 if (work_per_rank[i] == max_work) {
516 fmt::print("{}", fmt::styled(tmp, fmt::fg(fmt::color::red)));
517 }
518 else if (work_per_rank[i] == min_work) {
519 fmt::print("{}", fmt::styled(tmp, fmt::fg(fmt::color::green)));
520 }
521 else {
522 fmt::print("{}", tmp);
523 }
524 #else
525 fmt::print("{}", tmp);
526 #endif
527 }
528 }
529
530 // Imbalance penalty -- max work / avg work. If perfect balance, then all processors would have
531 // "avg_work" work to do. With current decomposition, every processor has to wait until
532 // "max_work" is done. Penalty = max_work / avg_work.
533 fmt::print("\nImbalance Penalty:\n\tMaximum Work = {}, Average Work = {}, Penalty (max/avg) "
534 "= {:.2f}\n\n",
535 fmt::group_digits(max_work), fmt::group_digits((size_t)avg_work),
536 (double)max_work / avg_work);
537
538 return std::make_pair(avg_work, median);
539 }
540
541 template <typename INT>
542 std::tuple<std::vector<double>, std::vector<double>, std::vector<double>>
543 DecompUtils::get_element_centroid(const Ioss::Region &region, IOSS_MAYBE_UNUSED INT dummy)
544 {
545 size_t element_count = region.get_property("element_count").get_int();
546
547 // The zoltan methods supported in slice are all geometry based
548 // and use the element centroid.
549 std::vector<double> x(element_count);
550 std::vector<double> y(element_count);
551 std::vector<double> z(element_count);
552
553 const auto *nb = region.get_node_blocks()[0];
554 std::vector<double> coor;
555 nb->get_field_data("mesh_model_coordinates", coor);
556
557 const auto &blocks = region.get_element_blocks();
558 size_t el = 0;
559 for (auto &eb : blocks) {
560 std::vector<INT> connectivity;
561 eb->get_field_data("connectivity_raw", connectivity);
562 size_t blk_element_count = eb->entity_count();
563 size_t blk_element_nodes = eb->topology()->number_nodes();
564
565 for (size_t j = 0; j < blk_element_count; j++) {
566 for (size_t k = 0; k < blk_element_nodes; k++) {
567 auto node = connectivity[j * blk_element_nodes + k] - 1;
568 x[el] += coor[node * 3 + 0];
569 y[el] += coor[node * 3 + 1];
570 z[el] += coor[node * 3 + 2];
571 }
572 x[el] /= blk_element_nodes;
573 y[el] /= blk_element_nodes;
574 z[el] /= blk_element_nodes;
575 el++;
576 }
577 }
578 return {x, y, z};
579 }
580
581 template IOSS_EXPORT std::tuple<std::vector<double>, std::vector<double>, std::vector<double>>
582 DecompUtils::get_element_centroid(const Ioss::Region &region, IOSS_MAYBE_UNUSED int dummy);
583
584 template IOSS_EXPORT std::tuple<std::vector<double>, std::vector<double>, std::vector<double>>
585 DecompUtils::get_element_centroid(const Ioss::Region &region, IOSS_MAYBE_UNUSED int64_t dummy);
586
587 } // namespace Ioss