Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
#include <algorithm>
#include <iomanip>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
 
#include "core/common/string_utils.h"
#include "core/framework/random_seed.h"
#include "core/graph/graph_utils.h"
#include "core/graph/graph_viewer.h"
#include "orttraining/core/optimizer/memory_optimizer/common.h"
#include "orttraining/core/optimizer/memory_optimizer/optimization_planner.h"
#include "orttraining/core/optimizer/memory_optimizer/recompute_analysis.h"
#include "orttraining/core/optimizer/memory_optimizer/memory_insight.h"
#include "orttraining/core/optimizer/memory_optimizer/transformer_specific.h"
 
namespace onnxruntime::optimizer::memory_optimizer {
 
// Placeholder string for table row separator, which is used to be replaced by table row separator finally.
constexpr const char kTableRowSeparator[] = "TABLE_SEPARATOR_PLACEHOLDER";
// Placeholder string for table border, which is used to be replaced by table border finally.
constexpr const char kTableBorder[] = "TABLE_BORDER_PLACEHOLDER";
 
// The max length of the first column in the table.
constexpr const int kFirstColumnWidth = 7;
// The max length of left part (e.g. title) in the second column.
constexpr const int kTitleWidthInSecondColumn = 15;
 
/**
 * @brief Prepare info including activation usage, node usage in fw and bw.
 *
 * @param graph Graph to iterate.
 * @param boundary_op_order_in_topological_sort index of the boundary op between fw and bw.
 * @param node_index_to_its_order_in_topological_sort_map The mapping of node index to its order in topological sort.
 * @param fw_op_output_arg_used_map Collected activation usage mapping.
 *   - key: node arg name
 *   - value: a pair of bool, representing whether the activation is used by forward nodes or by backward nodes.
 */
void GetForwardOutputUsageMap(const GraphViewer& graph_viewer,
                              const ptrdiff_t boundary_op_order_in_topological_sort,
                              const InlinedHashMap<NodeIndex, size_t>&
                                  node_index_to_its_order_in_topological_sort_map,
                              ActivationUsedMap& fw_op_output_arg_used_map) {
  ORT_ENFORCE(boundary_op_order_in_topological_sort >= 0);
  const auto& node_ids = graph_viewer.GetNodesInTopologicalOrder(TOPOLOGICAL_SORT_ALGORITHM);
 
  auto is_forward_pass_operator = [](ptrdiff_t op_order_in_topological_sort,
                                     ptrdiff_t boundary_op_order_in_topological_sort) -> bool {
    return op_order_in_topological_sort <= boundary_op_order_in_topological_sort;
  };
 
  fw_op_output_arg_used_map.clear();
  fw_op_output_arg_used_map.reserve(node_ids.size());
  for (size_t i = 0; i < node_ids.size(); ++i) {
    const Node* p_node = graph_viewer.GetNode(node_ids[i]);
    if (p_node == nullptr /* skip removed nodes*/) {
      continue;
    }
 
    const Node& node = *p_node;
    bool is_forward_op = is_forward_pass_operator(static_cast<ptrdiff_t>(i), boundary_op_order_in_topological_sort);
    if (!is_forward_op) {
      continue;
    }
 
    for (auto& output_arg : node.OutputDefs()) {
      if (!output_arg->Exists() || output_arg->Name().empty()) {
        continue;
      }
 
      bool used_in_fw = false;
      bool used_in_bw = false;
      for (auto& consumer_node : graph_viewer.GetConsumerNodes(output_arg->Name())) {
        ORT_ENFORCE(consumer_node != nullptr, "Consumer node should not be null.");
        auto it = node_index_to_its_order_in_topological_sort_map.find(consumer_node->Index());
        ORT_ENFORCE(it !=
                        node_index_to_its_order_in_topological_sort_map.end(),
                    "Consumer node should be in topological order map.");
        size_t consumer_node_index_in_topological_order = it->second;
        if (is_forward_pass_operator(static_cast<ptrdiff_t>(consumer_node_index_in_topological_order),
                                     boundary_op_order_in_topological_sort)) {
          used_in_fw = true;
        } else {
          used_in_bw = true;
        }
      }
 
      ORT_ENFORCE(fw_op_output_arg_used_map.find(output_arg->Name()) == fw_op_output_arg_used_map.end(),
                  "Duplicated output arg found named: ", output_arg->Name());
      fw_op_output_arg_used_map.insert({{output_arg->Name(), std::make_pair(used_in_fw, used_in_bw)}});
    }
  }
}
 
/**
 * @brief Find all stashed activations, e.g. activations used by forward operators and backward operators.
 *
 * @param graph_viewer Graph to iterate.
 * @param boundary_op_order_in_topological_sort The order of the boundary op in the topological sort.
 * @param candidate_output_args_map Candidate activations generated in forward, and are consumed by backward ops.
 * @param logger Logger.
 * @return Status
 */
 
Status GetStashedActivationCandidates(const GraphViewer& graph_viewer,
                                      const ptrdiff_t boundary_op_order_in_topological_sort,
                                      InlinedHashMap<const Node*, InlinedVector<size_t>>&
                                          candidate_output_args_map,
                                      const logging::Logger& logger) {
  if (boundary_op_order_in_topological_sort < 0) {
    MO_LOG_DEBUG_INFO(logger, "No boundary op found. Skip memory optimization.");
    return Status::OK();
  }
 
  const auto& node_ids = graph_viewer.GetNodesInTopologicalOrder(TOPOLOGICAL_SORT_ALGORITHM);
 
  InlinedHashMap<NodeIndex, size_t> node_index_to_its_order_in_topological_sort_map;
  for (size_t i = 0; i < node_ids.size(); ++i) {
    const Node* p_node = graph_viewer.GetNode(node_ids[i]);
    if (p_node == nullptr) { /* skip removed nodes*/
      continue;
    }
 
    node_index_to_its_order_in_topological_sort_map[p_node->Index()] = i;
  }
 
  ActivationUsedMap fw_op_output_arg_used_map;
  GetForwardOutputUsageMap(graph_viewer, boundary_op_order_in_topological_sort,
                           node_index_to_its_order_in_topological_sort_map,
                           fw_op_output_arg_used_map);
 
  for (auto& kv : fw_op_output_arg_used_map) {
    const auto& fw_out_arg = kv.first;
    const Node* n = graph_viewer.GetProducerNode(fw_out_arg);
    // Node run in forward pass, and the result is used by bw, then it is a candidate.
    if (kv.second.second) {
      ORT_ENFORCE(n, "Activation should have a producer node");
      size_t k = 0;
      for (k = 0; k < n->OutputDefs().size(); ++k) {
        if (n->OutputDefs()[k]->Name().compare(fw_out_arg) == 0) {
          break;
        }
      }
 
      if (std::find(candidate_output_args_map[n].begin(), candidate_output_args_map[n].end(), k) !=
          candidate_output_args_map[n].end()) {
        ORT_ENFORCE(false, "Duplicated candidate output found.");
      }
 
      candidate_output_args_map[n].push_back(k);
      MO_LOG_DEBUG_INFO(logger, "Find candidate output named [" + kv.first + "] of Node " +
                                    n->Name() + "(" + n->OpType() + ")");
    }
  }
 
  return Status::OK();
}
 
Status FindORTModuleMemoryOpportunity(const GraphViewer& graph_viewer,
                                      const ProbeConfig& probe_config,
                                      const logging::Logger& logger,
                                      InlinedHashMap<NodeIndex, ptrdiff_t>&
                                          node_index_to_its_order_in_topological_sort_map,
                                      ptrdiff_t& yield_op_order_in_topological_sort,
                                      InlinedHashMap<const Node*, InlinedVector<size_t>>&
                                          candidate_output_args_map,
                                      MemoryOptimizationPlanner& memory_opt_planner) {
  const auto& node_ids = graph_viewer.GetNodesInTopologicalOrder(TOPOLOGICAL_SORT_ALGORITHM);
 
  // Find boundary ops between forward and backward pass, currently, it's limited to YieldOp.
  yield_op_order_in_topological_sort = -1;
  for (size_t i = 0; i < node_ids.size(); ++i) {
    const Node* p_node = graph_viewer.GetNode(node_ids[i]);
    if (p_node == nullptr) { /* skip removed nodes*/
      continue;
    }
 
    if (p_node->OpType() == "YieldOp") {
      if (yield_op_order_in_topological_sort != -1) {
        return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "There are multiple YieldOps in the graph, node: ",
                               p_node->Name(), " is the second one.");
      }
      yield_op_order_in_topological_sort = static_cast<ptrdiff_t>(i);
    }
 
    node_index_to_its_order_in_topological_sort_map[p_node->Index()] = static_cast<ptrdiff_t>(i);
  }
 
  ORT_RETURN_IF_ERROR(GetStashedActivationCandidates(graph_viewer,
                                                     yield_op_order_in_topological_sort,
                                                     candidate_output_args_map,
                                                     logger));
 
  InlinedVector<const Node*> layer_boundary_ln_nodes;
  FindLayerBoundaryLayerNormNodes(graph_viewer, logger, node_index_to_its_order_in_topological_sort_map,
                                  yield_op_order_in_topological_sort, layer_boundary_ln_nodes);
 
  if (probe_config.enable_transformer_layer_as_boundary && layer_boundary_ln_nodes.size() == 0) {
    LOGS(logger, WARNING) << "No transformer layer boundary nodes found, this might cause memory optimization "
                             "not working as expected. Please check the model and the configuration.";
  }
 
  // The first pass - find the candidate subgraphs.
  for (int i = static_cast<int>(node_ids.size()) - 1; i >= 0; --i) {
    const Node* p_node = graph_viewer.GetNode(node_ids[i]);
    if (p_node == nullptr) {
      continue;
    }
 
    if (candidate_output_args_map.find(p_node) == candidate_output_args_map.end()) {
      continue;
    }
 
    bool can_compromise_stashed_activation = false;
    std::unique_ptr<NodeRecomputePlan> recompute_plan =
        CheckNodeForRecompute(graph_viewer,
                              *p_node,
                              probe_config,
                              node_index_to_its_order_in_topological_sort_map,
                              candidate_output_args_map,
                              layer_boundary_ln_nodes,
                              logger, false,
                              can_compromise_stashed_activation);
    if (recompute_plan != nullptr) {
      memory_opt_planner.AddNodeOptimizationPlan(p_node, std::move(recompute_plan));
    }
 
    // Only detect compromise recompute when recompute is not found, in case there are multiple recompute plans
    // for the same named activations, then user might enable those conflicting recompute plans by mistakes.
    if (recompute_plan == nullptr && can_compromise_stashed_activation) {
      MO_LOG_DEBUG_INFO(logger, "Searching Node " + p_node->Name() + "(" + p_node->OpType() +
                                    ") for compromised recompute");
      // If the subgraph recompute can save memory by comprising the assumption - recompute graphs' input must exist
      // during backward pass, then we can consider to recompute them.
      std::unique_ptr<NodeRecomputePlan> recompute_with_compromise_plan =
          CheckNodeForRecompute(graph_viewer, *p_node, probe_config,
                                node_index_to_its_order_in_topological_sort_map,
                                candidate_output_args_map,
                                layer_boundary_ln_nodes,
                                logger, true,
                                can_compromise_stashed_activation);
      if (recompute_with_compromise_plan != nullptr) {
        memory_opt_planner.AddNodeOptimizationPlan(p_node, std::move(recompute_with_compromise_plan));
      }
    }
  }
 
  return Status::OK();
}
 
void GetMemoryRecordsGroupedByNodeClusterId(const MemoryOptimizationPlanner& memory_opt_planner,
                                            const NodeToClusterApplyContextMap& node_to_apply_contexts_map,
                                            std::vector<std::pair<std::string, MemoryRecord>>& generated_records) {
  // Group by node cluster id, generate memory record.
  InlinedHashMap<std::string, MemoryRecord> records;
  const auto& node_to_optimization_plan_map = memory_opt_planner.GetNodeToOptimizationPlanMap();
  for (const auto& node_to_optimization_plan : node_to_optimization_plan_map) {
    const auto& node = node_to_optimization_plan.first;
    const auto& node_plans = node_to_optimization_plan.second;
    const std::string node_cluster_id = memory_opt_planner.GenerateNodeClusterId(node);
 
    std::pair<InlinedHashMap<std::string, MemoryRecord>::iterator, bool> insert_result =
        records.insert({node_cluster_id, MemoryRecord()});
    bool already_exist = !insert_result.second;
    auto& record = insert_result.first->second;
    record.freq++;
 
    // Collect more information for display.
    for (auto& plan : node_plans) {
      // Same node cluster id, plans might still have different reuse_buffer patterns, so we need to collect all of them.
      if (plan->reuse_buffers.size() > 0) {
        gsl::span<const size_t> output_indices = plan->GetActivationOutputIndices();
        for (auto output_index : output_indices) {
          bool is_output_reusing_buffers = plan->reuse_buffers.find(output_index) != plan->reuse_buffers.end();
          if (plan->GetOptimizationType() == OptimizationType::RecomputeWithCompromise) {
            if (is_output_reusing_buffers) {
              record.output_port_reuse_recompute_with_compromise_count[output_index] += 1;
            }
          } else if (plan->GetOptimizationType() == OptimizationType::Recompute) {
            if (is_output_reusing_buffers) {
              record.output_port_reuse_recompute_count[output_index] += 1;
            }
          }
        }
      }
 
      // For other infos that are guaranteed identity by cluster id, just skip collecting.
      if (already_exist) {
        continue;
      }
 
      if (plan->GetOptimizationType() == OptimizationType::RecomputeWithCompromise) {
        record.recompute_with_compromise_subgraph_str =
            dynamic_cast<NodeRecomputePlan*>(plan.get())->GetNodesInTopoOrderStr();
      } else if (plan->GetOptimizationType() == OptimizationType::Recompute) {
        record.recompute_subgraph_str = dynamic_cast<NodeRecomputePlan*>(plan.get())->GetNodesInTopoOrderStr();
      }
 
      gsl::span<const size_t> output_indices = plan->GetActivationOutputIndices();
      for (auto output_index : output_indices) {
        const auto& output_def = node->OutputDefs()[output_index];
        MLDataType ml_data_type = DataTypeImpl::TypeFromProto(*output_def->TypeAsProto());
        ORT_ENFORCE(ml_data_type->IsTensorType(), "ml_type must be a tensor type, but it is ",
                    DataTypeImpl::ToString(ml_data_type));
        const TensorTypeBase* tensor_type_base = ml_data_type->AsTensorType();
        ORT_ENFORCE(nullptr != tensor_type_base);
        MLDataType elt_type = tensor_type_base->GetElementType();
 
        const auto byte_count_per_element = elt_type->Size();
        if (plan->GetOptimizationType() == OptimizationType::RecomputeWithCompromise) {
          record.compromise_recomputed_outputs.emplace_back(
              output_index,
              plan->GetActivationOutputDimParamString(output_index),
              byte_count_per_element,
              plan->GetSaveRatio());
 
        } else if (plan->GetOptimizationType() == OptimizationType::Recompute) {
          record.recomputed_outputs.emplace_back(output_index,
                                                 plan->GetActivationOutputDimParamString(output_index),
                                                 byte_count_per_element,
                                                 plan->GetSaveRatio());
        }
      }
    }
  }
 
  // Sort by feq and then by record key, to make sure the output is deterministic.
  InlinedVector<std::pair<int, std::string>> freq_to_record_key;
  for (const auto& p : records) {
    freq_to_record_key.push_back({p.second.freq, p.first});
  }
 
  std::sort(freq_to_record_key.begin(), freq_to_record_key.end(), [](auto& left, auto& right) {
    if (left.first == right.first) {
      return left.second.compare(right.second) > 0;
    }
    return left.first > right.first;
  });
 
  for (const auto& p : freq_to_record_key) {
    const std::string record_key = p.second;
    generated_records.push_back({record_key, records[record_key]});
  }
 
  // If apply context is provided, also update the actual applied count.
  // Be noted, node_to_apply_contexts_map contains some or all of the nodes in node_to_optimization_plan_map.
  if (node_to_apply_contexts_map.size() > 0) {
    InlinedHashMap<std::string, MemoryRecord*> node_cluster_id_to_record_map;
    for (auto& p : generated_records) {
      node_cluster_id_to_record_map[p.first] = &p.second;
    }
 
    for (const auto& p : node_to_apply_contexts_map) {
      const auto& node = p.first;
      const auto& apply_context = p.second;
      std::string node_cluster_id = memory_opt_planner.GenerateNodeClusterId(node);
 
      ORT_ENFORCE(node_cluster_id_to_record_map.find(node_cluster_id) != node_cluster_id_to_record_map.end(),
                  "Node cluster id not found in memory record map: ", node_cluster_id);
 
      if (apply_context->type == OptimizationType::Recompute) {
        node_cluster_id_to_record_map[node_cluster_id]->actual_recompute_count += 1;
        node_cluster_id_to_record_map[node_cluster_id]->request_recompute_count = apply_context->requested_count;
      } else if (apply_context->type == OptimizationType::RecomputeWithCompromise) {
        node_cluster_id_to_record_map[node_cluster_id]->actual_recompute_with_compromise_count += 1;
        node_cluster_id_to_record_map[node_cluster_id]->request_recompute_with_compromise_count =
            apply_context->requested_count;
      } else {
        ORT_THROW("Unsupported optimization type found.");
      }
    }
  }
}
 
// Function declare to make it compile.
void IterateNodeOptimizationPlan(const std::shared_ptr<NodeOptimizationPlanBase>& plan,
                                 const InlinedHashMap<const Node*, InlinedVector<std::shared_ptr<NodeOptimizationPlanBase>>>&
                                     node_to_optimization_plans_map,
                                 const InlinedVector<std::shared_ptr<NodeOptimizationPlanBase>>&
                                     current_combination,
                                 const logging::Logger& logger,
                                 InlinedVector<InlinedVector<std::shared_ptr<NodeOptimizationPlanBase>>>&
                                     all_combinations);
 
/*
 * Iterate from a node, generate combinations for each optimization plan for it.
 */
void IterateNode(const Node* node,
                 const InlinedHashMap<const Node*, InlinedVector<std::shared_ptr<NodeOptimizationPlanBase>>>&
                     node_to_optimization_plans_map,
                 const InlinedVector<std::shared_ptr<NodeOptimizationPlanBase>>&
                     current_combination,
                 const logging::Logger& logger,
                 InlinedVector<InlinedVector<std::shared_ptr<NodeOptimizationPlanBase>>>&
                     all_combinations) {
  MO_LOG_DEBUG_INFO(logger, "Enter IterateNode: " + node->Name());
  if (node_to_optimization_plans_map.find(node) == node_to_optimization_plans_map.end()) {
    MO_LOG_DEBUG_INFO(logger, "Exit IterateNode since reused node don't have optimization plans: " + node->Name());
    return;
  }
 
  for (const std::shared_ptr<NodeOptimizationPlanBase>& plan : node_to_optimization_plans_map.at(node)) {
    if (std::find(current_combination.begin(), current_combination.end(), plan) !=
        current_combination.end()) {
      continue;
    }
    InlinedVector<std::shared_ptr<NodeOptimizationPlanBase>> new_combination = current_combination;
    new_combination.push_back(plan);
    IterateNodeOptimizationPlan(plan, node_to_optimization_plans_map, new_combination, logger, all_combinations);
  }
  MO_LOG_DEBUG_INFO(logger, "Exit IterateNode: " + node->Name());
}
 
void ListAllCombinations(const InlinedVector<InlinedVector<InlinedVector<std::shared_ptr<NodeOptimizationPlanBase>>>>&
                             all_possible_node_optimization_plans,
                         int index,
                         const InlinedVector<std::shared_ptr<NodeOptimizationPlanBase>>& current_combination,
                         const logging::Logger& logger,
                         InlinedVector<InlinedVector<std::shared_ptr<NodeOptimizationPlanBase>>>&
                             all_combinations) {
  MO_LOG_DEBUG_INFO(logger, "Enter ListAllCombinations");
  if (index == static_cast<int>(all_possible_node_optimization_plans.size())) {
    if (std::find(all_combinations.begin(), all_combinations.end(), current_combination) ==
        all_combinations.end()) {
      all_combinations.push_back(current_combination);
    }
    MO_LOG_DEBUG_INFO(logger, "Exit ListAllCombinations after finding a new combination");
    return;
  }
 
  const InlinedVector<InlinedVector<std::shared_ptr<NodeOptimizationPlanBase>>>&
      plan_combination_list_at_cur_index = all_possible_node_optimization_plans[index];
  // For the index-th reused buffer, iterate all possible complete plans.
  for (size_t i = 0; i < plan_combination_list_at_cur_index.size(); ++i) {
    const auto& plan_combination = plan_combination_list_at_cur_index[i];
    InlinedVector<std::shared_ptr<NodeOptimizationPlanBase>> new_combination = current_combination;
    // Append the chosen complete plan and continue exploring the next reused buffer by index + 1.
    new_combination.insert(new_combination.end(), plan_combination.begin(), plan_combination.end());
    ListAllCombinations(all_possible_node_optimization_plans, index + 1, new_combination, logger, all_combinations);
  }
 
  MO_LOG_DEBUG_INFO(logger, "Exit ListAllCombinations");
}
 
/**
 * Iterate from a node optimization plan, if there is any buffer reuse in its node outputs,
 * iterate all possible reuse buffer plan combinations.
 */
void IterateNodeOptimizationPlan(const std::shared_ptr<NodeOptimizationPlanBase>& plan,
                                 const InlinedHashMap<const Node*, InlinedVector<std::shared_ptr<NodeOptimizationPlanBase>>>&
                                     node_to_optimization_plans_map,
                                 const InlinedVector<std::shared_ptr<NodeOptimizationPlanBase>>&
                                     current_combination,
                                 const logging::Logger& logger,
                                 InlinedVector<InlinedVector<std::shared_ptr<NodeOptimizationPlanBase>>>&
                                     all_combinations) {
  MO_LOG_DEBUG_INFO(logger, "Enter IterateNodeOptimizationPlan: " + plan->GetClusterId());
 
  // No reuse buffer, don't need to iterate further, we found a plan combination already.
  if (plan->reuse_buffers.size() == 0) {
    MO_LOG_DEBUG_INFO(logger, "length of current_combination: " +
                                  std::to_string(current_combination.size()) + ", " + plan->GetClusterId());
    all_combinations.push_back(current_combination);
    MO_LOG_DEBUG_INFO(logger, "Exit IterateNodeOptimizationPlan");
    return;
  }
 
  InlinedVector<InlinedVector<InlinedVector<std::shared_ptr<NodeOptimizationPlanBase>>>>
      all_possible_node_optimization_plans(plan->reuse_buffers.size());
 
  size_t i = 0;
  for (const auto& p : plan->reuse_buffers) {
    MO_LOG_DEBUG_INFO(logger, ">>>reuse buffer: " + std::to_string(p.first));
    // If the resued node is part of current node optimization plan, then we just add current combination to the result.
    if (plan->GetOptimizationType() == OptimizationType::RecomputeWithCompromise || plan->GetOptimizationType() == OptimizationType::Recompute) {
      const auto& recompute_subgraph =
          dynamic_cast<NodeRecomputePlan*>(plan.get())->GetNodesInTopoOrder();
      if (std::find(recompute_subgraph.begin(), recompute_subgraph.end(), p.second.first) != recompute_subgraph.end()) {
        all_possible_node_optimization_plans[i].push_back(current_combination);
      }
    }
 
    if (all_possible_node_optimization_plans[i].size() == 0) {
      IterateNode(p.second.first, node_to_optimization_plans_map, current_combination, logger, all_possible_node_optimization_plans[i]);
    }
 
    ++i;
  }
 
  ListAllCombinations(all_possible_node_optimization_plans, 0, {}, logger, all_combinations);
 
  MO_LOG_DEBUG_INFO(logger, "Exit IterateNodeOptimizationPlan: " + plan->GetClusterId());
}
 
// Return a deterministic string for multiple plans combinations.
std::string GetMultiplePlanClusterId(const InlinedVector<std::shared_ptr<NodeOptimizationPlanBase>>& plans) {
  constexpr const int request_count = -1;  // -1 means apply optimization to all appearances.
 
  std::ostringstream oss;
  InlinedVector<std::string> sorted_plans;
  for (const auto& plan : plans) {
    sorted_plans.push_back(plan->GetClusterId() + ":" + std::to_string(static_cast<int>(plan->GetOptimizationType())) +
                           ":" + std::to_string(request_count));
  }
 
  std::sort(sorted_plans.begin(), sorted_plans.end());
 
  for (const auto& plan : sorted_plans) {
    if (oss.str().size() > 0) {
      oss << ",";
    }
    oss << plan;
  }
  return oss.str();
}
 
void GetMemorySavingSymbolicString(const MemoryOptimizationPlanner& memory_opt_planner,
                                   const logging::Logger& logger,
                                   std::map<std::string, std::pair<std::string, int>>&
                                       combination_cluster_ids_to_saved_symbolic_byte_map) {
  // Group by "ClusterId:OptimizationType:RequestCount".
  InlinedVector<InlinedVector<std::shared_ptr<NodeOptimizationPlanBase>>> all_combinations;
 
  combination_cluster_ids_to_saved_symbolic_byte_map.clear();
  const auto& node_to_optimization_plan_map = memory_opt_planner.GetNodeToOptimizationPlanMap();
  for (const auto& node_to_optimization_plan : node_to_optimization_plan_map) {
    const auto& node = node_to_optimization_plan.first;
    InlinedVector<std::shared_ptr<NodeOptimizationPlanBase>> current_combination;
    MO_LOG_DEBUG_INFO(logger, ">>>Start looping node: " + node->Name());
    IterateNode(node, node_to_optimization_plan_map, current_combination, logger, all_combinations);
    MO_LOG_DEBUG_INFO(logger, "<<<End looping node: " + node->Name());
  }
 
  for (const auto& combination : all_combinations) {
    std::string combination_cluster_id = GetMultiplePlanClusterId(combination);
    std::string symbolic_byte_count = "";
    for (const auto& plan : combination) {
      if (symbolic_byte_count.size() > 0) {
        symbolic_byte_count += " + ";
      }
      symbolic_byte_count += plan->GetMemorySavingSymbolicString();
    }
 
    if (symbolic_byte_count.size() > 0) {
      symbolic_byte_count = "(" + symbolic_byte_count + ")";
    }
    auto& p = combination_cluster_ids_to_saved_symbolic_byte_map[combination_cluster_id];
    const auto& original = p.first;
    if (original.size() > 0) {
      symbolic_byte_count = original + " + " + symbolic_byte_count;
    }
 
    MO_LOG_DEBUG_INFO(logger, "combination_cluster_id: " + combination_cluster_id +
                                  ", symbolic_byte_count: " + symbolic_byte_count);
 
    p.first = symbolic_byte_count;
    p.second += 1;
  }
}
 
namespace {
 
template <typename T>
std::string ToFixedLengthString(T value, int length) {
  std::ostringstream oss;
  oss << std::setw(length) << std::left;
  oss << value;
  return oss.str();
}
 
void FormatRecomputeMemoryRecords(int option_index,
                                  const MemoryRecord& record,
                                  bool compromise_recompute,
                                  InlinedVector<std::string>& rows) {
  const auto subgraph_str = compromise_recompute ? record.recompute_with_compromise_subgraph_str
                                                 : record.recompute_subgraph_str;
  const auto opt_type = compromise_recompute ? OptimizationType::RecomputeWithCompromise
                                             : OptimizationType::Recompute;
  const auto request_count = compromise_recompute ? record.request_recompute_with_compromise_count
                                                  : record.request_recompute_count;
  const auto actual_count = compromise_recompute ? record.actual_recompute_with_compromise_count
                                                 : record.actual_recompute_count;
 
  const std::string empty_first_col = "|" + ToFixedLengthString(std::string(), kFirstColumnWidth) + "|";
 
  rows.push_back(empty_first_col);
  rows.push_back(empty_first_col +
                 ToFixedLengthString(">>Option " + std::to_string(option_index), kTitleWidthInSecondColumn) + ": " +
                 OptimizationTypeToString(opt_type) + " subgraph " + subgraph_str);
 
  if (request_count) {
    // Only show this if user requested it.
    rows.push_back(
        empty_first_col +
        ToFixedLengthString("  Status", kTitleWidthInSecondColumn) + ": " + "Enabled, requested count=" +
        std::to_string(request_count) +
        ", actual applied count=" + std::to_string(actual_count));
  } else {
    rows.push_back(empty_first_col + ToFixedLengthString("  Status", kTitleWidthInSecondColumn) +
                   ": Disabled.");
  }
 
  std::string activation_str = empty_first_col + "  Stashed Activations: ";
  rows.push_back(activation_str);
 
  const auto& reused_buffers = compromise_recompute ? record.output_port_reuse_recompute_with_compromise_count
                                                    : record.output_port_reuse_recompute_count;
  if (reused_buffers.size() > 0) {
    std::string reused_buffers_summary = empty_first_col + ToFixedLengthString("   - ReuseFreq", kTitleWidthInSecondColumn) + ": ";
    for (const auto& p : reused_buffers) {
      reused_buffers_summary += " Output " + std::to_string(p.first) + "(" + std::to_string(p.second) + "),";
    }
 
    rows.push_back(reused_buffers_summary);
  }
 
  const auto activation_count = compromise_recompute ? record.compromise_recomputed_outputs.size()
                                                     : record.recomputed_outputs.size();
  for (size_t i = 0; i < activation_count; ++i) {
    const MemoryRecord::OutputStat* stat;
    if (compromise_recompute) {
      stat = &record.compromise_recomputed_outputs[i];
    } else {
      stat = &record.recomputed_outputs[i];
    }
 
    rows.push_back(empty_first_col +
                   ToFixedLengthString("   - Output " + std::to_string(stat->output_index), kTitleWidthInSecondColumn) +
                   ": [" + stat->output_shape_str + "], byte/elem: " +
                   std::to_string(stat->output_byte_count_per_element) +
                   ", " + std::to_string(static_cast<int>(stat->saving_ratio * 100)) +
                   "% saved");
  }
}
}  // namespace
 
std::string SerializeMemoryRecords(
    const std::vector<std::pair<std::string, MemoryRecord>>& records_grouped_by_node_cluster_id,
    std::string_view memory_optimization_config_file_path) {
  InlinedVector<std::string> rows;
  rows.push_back(kTableBorder);
  rows.push_back("|" + ToFixedLengthString("Freq", kFirstColumnWidth) +
                 "| Memory Optimization Opportunities (Clustered by node-level activation patterns)");
  rows.push_back(kTableRowSeparator);
 
  for (const auto& p : records_grouped_by_node_cluster_id) {
    const auto& record = p.second;
    rows.push_back("|" + ToFixedLengthString(record.freq, kFirstColumnWidth) +
                   "|For each row options are mutually exclusive, only one of them can be enabled.");
 
    int option_index = 1;
    if (record.recomputed_outputs.size() > 0) {
      FormatRecomputeMemoryRecords(option_index, record, false, rows);
      option_index++;
    }
 
    if (record.compromise_recomputed_outputs.size() > 0) {
      FormatRecomputeMemoryRecords(option_index, record, true, rows);
      option_index++;
    }
    rows.push_back(kTableRowSeparator);
  }
 
  rows.push_back(kTableBorder);
 
  size_t max_length = 0;
  for (auto& row : rows) {
    max_length = std::max(max_length, row.length());
  }
 
  // Example is:
  // static const std::string row_separator =
  //     "|_ _ _ _|_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _|\n";
  static const std::string kTableRowSeparatorStart = "|_ _ _ _|";
  size_t second_row_length = max_length - kTableRowSeparatorStart.length();
  if (second_row_length % 2 == 0) {
    second_row_length += 2;
    max_length += 2;
  } else {
    second_row_length += 3;  // add 3 to make it even
    max_length += 3;
  }
  std::string row_separator_full(second_row_length, ' ');
  for (size_t i = 0; i < row_separator_full.size() - 1; ++i) {
    if (i % 2 == 0) {
      row_separator_full[i] = '_';
    }
  }
  row_separator_full[row_separator_full.size() - 1] = '|';
  row_separator_full = kTableRowSeparatorStart + row_separator_full;
 
  std::string table_border_full(max_length, '=');
  std::ostringstream summary;
  summary << std::endl;
  summary << MakeString("MemoryInsight Summary - User config file path: ",
                        (memory_optimization_config_file_path.empty()
                             ? "not provided"
                             : memory_optimization_config_file_path))
          << std::endl;
  for (auto& row : rows) {
    if (row == kTableRowSeparator) {
      summary << row_separator_full << std::endl;
    } else if (row == kTableBorder) {
      summary << table_border_full << std::endl;
    } else {
      std::string filled_up = std::string(max_length - row.length(), ' ');
      filled_up[filled_up.length() - 1] = '|';
      summary << row << filled_up << std::endl;
    }
  }
  summary << "Note: use comma as a separator for enabling more than one subgraphs." << std::endl;
  return summary.str();
}
 
std::string GetSerializedORTModuleMemoryStat(const GraphViewer& graph_viewer,
                                             std::string_view memory_optimization_config_file_path,
                                             std::string_view recompute_probe_config,
                                             const bool return_opportunity_table,
                                             const logging::Logger& logger,
                                             std::map<std::string, std::pair<std::string, int>>&
                                                 cluster_id_combinations_to_saved_symbolic_byte_map,
                                             const OrtValueNameIdxMap* ortvalue_name_to_idx_map,
                                             const SequentialExecutionPlan* p_seq_exec_plan) {
  ProbeConfig probe_config;
  ORT_ENFORCE(ParseProbeConfigFromString(recompute_probe_config, probe_config).IsOK());
 
  ptrdiff_t yield_op_order_in_topological_sort;
  InlinedHashMap<const Node*, InlinedVector<size_t>> candidate_output_args_map;
  InlinedHashMap<NodeIndex, ptrdiff_t> node_index_to_its_order_in_topological_sort_map;
 
  // The first pass - find the candidate subgraphs.
  MemoryOptimizationPlanner memory_opt_planner;
  ORT_ENFORCE(FindORTModuleMemoryOpportunity(
                  graph_viewer,
                  probe_config,
                  logger,
                  node_index_to_its_order_in_topological_sort_map,
                  yield_op_order_in_topological_sort,
                  candidate_output_args_map,
                  memory_opt_planner)
                  .IsOK());
 
  InlinedHashMap<std::string, UserConfig> cluster_id_to_config_map;
  // Finalize the plan according to user config,
  // then create a ClusterApplyContext for each unique cluster (having the same node pattern)
 
  NodeToClusterApplyContextMap node_to_apply_context_map;
 
  if (!memory_optimization_config_file_path.empty()) {
    ORT_ENFORCE(ParseOptimizationConfigFromString(memory_optimization_config_file_path, cluster_id_to_config_map)
                    .IsOK());
    InlinedHashMap<const Node*, std::shared_ptr<NodeOptimizationPlanBase>> node_to_opt_plan_map;
    ORT_ENFORCE(memory_opt_planner.FinalizeNodePlansFromUserConfig(cluster_id_to_config_map,
                                                                   node_to_opt_plan_map,
                                                                   node_to_apply_context_map)
                    .IsOK());
  }
 
  if (ortvalue_name_to_idx_map != nullptr && p_seq_exec_plan != nullptr) {
    ORT_ENFORCE(memory_opt_planner.UpdateNodePlansFromExecutionPlan(graph_viewer,
                                                                    *ortvalue_name_to_idx_map,
                                                                    *p_seq_exec_plan)
                    .IsOK());
  }
 
  GetMemorySavingSymbolicString(memory_opt_planner, logger, cluster_id_combinations_to_saved_symbolic_byte_map);
 
  if (return_opportunity_table) {
    std::vector<std::pair<std::string, MemoryRecord>> records;
    GetMemoryRecordsGroupedByNodeClusterId(memory_opt_planner, node_to_apply_context_map, records);
    return SerializeMemoryRecords(records, memory_optimization_config_file_path);
  }
 
  // Otherwise, return empty.
  return "";
}
 
}  // namespace onnxruntime::optimizer::memory_optimizer