Исходный код СУБД 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
#include "core/framework/resource_accountant.h"
 
#include "core/common/inlined_containers.h"
#include "core/common/narrow.h"
#include "core/common/parse_string.h"
#include "core/common/safeint.h"
#include "core/common/string_utils.h"
 
#include "core/framework/config_options.h"
#include "core/framework/max_shape_override.h"
#include "core/framework/murmurhash3.h"
#include "core/framework/tensorprotoutils.h"
#include "core/graph/constants.h"
#include "core/graph/graph.h"
#include "core/session/onnxruntime_session_options_config_keys.h"
 
#include <algorithm>
#include <fstream>
#include <optional>
 
namespace onnxruntime {
 
void ConsolidateWorkspaceReservations(
    NodeWorkspaceReservationMap& reservations,
    gsl::span<const size_t> source_node_indices,
    size_t destination_node_index) {
  WorkspaceEstimateSelection aggregate;
  bool has_reservation = false;
  InlinedHashSet<size_t> matched_node_indices;
  const auto accumulate_reservation = [&aggregate, &has_reservation](
                                          const WorkspaceEstimateSelection& reservation) {
    aggregate.bytes =
        static_cast<size_t>(SafeInt<size_t>(aggregate.bytes) + reservation.bytes);
    aggregate.profiled_bytes =
        static_cast<size_t>(SafeInt<size_t>(aggregate.profiled_bytes) + reservation.profiled_bytes);
    aggregate.level1_estimated_bytes =
        static_cast<size_t>(SafeInt<size_t>(aggregate.level1_estimated_bytes) +
                            reservation.level1_estimated_bytes);
    aggregate.persistent_prepack_bytes =
        static_cast<size_t>(SafeInt<size_t>(aggregate.persistent_prepack_bytes) +
                            reservation.persistent_prepack_bytes);
    aggregate.initialization_scratch_bytes =
        std::max(aggregate.initialization_scratch_bytes, reservation.initialization_scratch_bytes);
    aggregate.source =
        !has_reservation || aggregate.source == reservation.source
            ? reservation.source
            : WorkspaceEstimateSource::kNone;
    has_reservation = true;
  };
 
  for (size_t node_index : source_node_indices) {
    const auto reservation_it = reservations.find(node_index);
    if (reservation_it == reservations.end() ||
        !matched_node_indices.insert(node_index).second) {
      continue;
    }
 
    accumulate_reservation(reservation_it->second);
  }
 
  if (!has_reservation) {
    return;
  }
 
  if (matched_node_indices.find(destination_node_index) == matched_node_indices.end()) {
    const auto destination_reservation_it = reservations.find(destination_node_index);
    if (destination_reservation_it != reservations.end()) {
      accumulate_reservation(destination_reservation_it->second);
    }
  }
 
  for (size_t node_index : matched_node_indices) {
    reservations.erase(node_index);
  }
  reservations.insert_or_assign(destination_node_index, aggregate);
}
 
// Accounts for resources represented as byte counts. Per-node costs can come from
// profiling statistics, ad-hoc fallback estimation, or an operator-specific estimator.
// This is currently used by CUDA EP.
class SizeBasedResourceAccountant : public IResourceAccountant {
  struct PendingWorkspaceEstimate {
    const void* graph_identity;
    WorkspaceEstimateSelection selection;
  };
 
 public:
  SizeBasedResourceAccountant() = default;
  ~SizeBasedResourceAccountant() = default;
 
  SizeBasedResourceAccountant(size_t threshold, InlinedHashMap<std::string, NodeAllocationStats>&& node_stats)
      : IResourceAccountant(threshold), node_stats_(std::move(node_stats)) {}
 
  explicit SizeBasedResourceAccountant(size_t threshold) : IResourceAccountant(threshold) {}
 
  explicit SizeBasedResourceAccountant(InlinedHashMap<std::string, NodeAllocationStats>&& node_stats)
      : IResourceAccountant(), node_stats_(std::move(node_stats)) {}
 
  ResourceCount GetConsumedAmount() const noexcept override {
    return consumed_amount_;
  }
 
  void AddConsumedAmount(const ResourceCount& amount) override {
    if (std::holds_alternative<size_t>(amount)) {
      consumed_amount_ =
          static_cast<size_t>(SafeInt<size_t>(consumed_amount_) + std::get<size_t>(amount));
    }
  }
  void RemoveConsumedAmount(const ResourceCount& amount) override {
    if (std::holds_alternative<size_t>(amount)) {
      consumed_amount_ =
          static_cast<size_t>(SafeInt<size_t>(consumed_amount_) - std::get<size_t>(amount));
    }
  }
 
  // Computes the resource cost for a candidate node.
  //
  // If profiling statistics are available, uses their non-workspace cost and
  // profiled temporary allocations. If a Level-1 runtime workspace estimate is
  // also provided, uses the maximum of the profiled and estimated workspace.
  // Without profiling, computes known initializer/output bytes and uses the
  // Level-1 runtime workspace or, when unavailable, fallback workspace.
  // Initializer bytes are charged separately, so persistent prepack estimates
  // must include only additional allocations, not storage reused directly from
  // an initializer (for example, an offline-prepacked weight). Persistent
  // prepack estimates are additional conservative charges in both paths.
  // Initialization scratch remains diagnostic rather than part of the additive
  // hard budget. MatMulNBits tactic profiling runs synchronously while
  // each kernel is constructed, and PrePack() calls run sequentially after
  // kernel creation; their scratch buffers are therefore created and released
  // one at a time. Their true session-wide requirement is a peak, which cannot
  // be represented by the reversible per-node ResourceCount scalar.
  //
  // GetCapability may probe nodes that are not ultimately assigned to this EP,
  // so per-node weights and workspace remain pending. CommitResourcesForNode()
  // promotes them after acceptance, while ResetForNewPass() discards state from
  // rejected or superseded capabilities.
  ResourceCount ComputeResourceCount(
      const Node& node, std::optional<Level1MemoryEstimate> level1_memory_estimate) override {
    if (node_stats_) {
      const auto node_name = MakeUniqueNodeName(node);
      auto hit = node_stats_->find(node_name);
      if (hit != node_stats_->end()) {
        const auto& stats = hit->second;
        const bool has_runtime_workspace_estimator =
            level1_memory_estimate.has_value() &&
            level1_memory_estimate->runtime_workspace_bytes.has_value();
        const size_t runtime_transient_bytes =
            level1_memory_estimate.has_value() ? level1_memory_estimate->runtime_transient_bytes : 0;
        const size_t level1_workspace_bytes =
            std::max(level1_memory_estimate.has_value()
                         ? level1_memory_estimate->runtime_workspace_bytes.value_or(0)
                         : 0,
                     runtime_transient_bytes);
        const bool has_estimator = has_runtime_workspace_estimator || runtime_transient_bytes > 0;
        const size_t selected_workspace =
            std::max(stats.total_temp_allocations, level1_workspace_bytes);
        const size_t persistent_prepack_bytes =
            level1_memory_estimate.has_value() ? level1_memory_estimate->persistent_prepack_bytes : 0;
        const size_t initialization_scratch_bytes =
            level1_memory_estimate.has_value() ? level1_memory_estimate->initialization_scratch_bytes : 0;
        pending_workspace_selection_by_node_.insert_or_assign(
            node.Index(),
            PendingWorkspaceEstimate{
                node.GetContainingGraph(),
                WorkspaceEstimateSelection{
                    selected_workspace,
                    has_estimator ? WorkspaceEstimateSource::kProfileAndEstimator
                                  : WorkspaceEstimateSource::kProfile,
                    stats.total_temp_allocations,
                    level1_workspace_bytes,
                    persistent_prepack_bytes,
                    initialization_scratch_bytes}});
        const SafeInt<size_t> resource_count =
            SafeInt<size_t>(stats.input_sizes) + stats.initializers_sizes +
            stats.total_dynamic_sizes + selected_workspace +
            persistent_prepack_bytes;
        return static_cast<size_t>(resource_count);
      }
 
      // Preserve the established partial-profile behavior: a node absent from
      // the stats file has zero cost. Falling through to ad-hoc accounting
      // would change existing partition decisions and mix profile-based costs
      // with initializer bookkeeping that the profile path does not use.
      return static_cast<size_t>(0);
    }
 
    const auto* graph = node.GetContainingGraph();
    if (!graph) return static_cast<size_t>(0);
    const auto& max_shapes = GetMaxShapeInferenceResult();
 
    SafeInt<size_t> total_size = 0;
    for (const auto* input_def : node.InputDefs()) {
      if (!input_def->Exists()) continue;
 
      const auto& name = input_def->Name();
      constexpr bool check_outer_scope = true;
      const auto* tensor_proto = graph->GetInitializer(name, check_outer_scope);
 
      if (tensor_proto) {
        // Skip if already committed from a previous partitioning iteration
        if (committed_weights_.count(name) > 0) {
          continue;
        }
 
        // Skip if already pending from another node in this GetCapability pass
        if (pending_weights_.count(name) > 0) {
          continue;
        }
 
        size_t size = 0;
        auto status = utils::GetSizeInBytesFromTensorProto<0>(*tensor_proto, &size);
 
        if (status.IsOK()) {
          total_size += size;
          pending_weights_.insert(name);
          pending_weights_by_node_[node.Index()].insert(name);
        }
      }
    }
 
    // Account for intermediate output tensors when shape info is available.
    // When max-shape inference is available, use it to resolve dynamic outputs.
    // Otherwise, GetSizeInBytesFromTensorTypeProto will only succeed when all dims
    // are known (static shape).
    SafeInt<size_t> output_size = 0;
    for (const auto* output_def : node.OutputDefs()) {
      if (!output_def->Exists() || !output_def->HasTensorOrScalarShape()) continue;
      const auto* type_proto = output_def->TypeAsProto();
      if (!type_proto || !utils::HasTensorType(*type_proto)) continue;
 
      size_t size = 0;
      // Try max-shape inference first for dynamic outputs
      if (!max_shapes.Empty()) {
        if (const TensorShape* max_shape =
                max_shapes.GetShape(graph, output_def->Name())) {
          const auto& tensor_type = type_proto->tensor_type();
          if (tensor_type.has_elem_type()) {
            const SafeInt<size_t> inferred_size =
                SafeInt<size_t>(max_shape->Size()) *
                utils::GetElementSizeOfTensor(
                    static_cast<ONNX_NAMESPACE::TensorProto_DataType>(tensor_type.elem_type()));
            size = inferred_size;
          }
        }
      }
      // Fall back to static shape
      if (size == 0 &&
          !utils::GetSizeInBytesFromTensorTypeProto<0>(type_proto->tensor_type(), &size).IsOK()) {
        continue;
      }
      output_size += size;
    }
 
    // Use the safety-margin portion as fallback workspace when no Level-1
    // estimate is available. Max-shape inference makes tensor sizes concrete
    // but does not, by itself, make kernel workspace requirements known.
    constexpr size_t kAdHocSafetyMultiplierPercent = 150;
    SafeInt<size_t> estimated = total_size + output_size;
    const size_t fallback_workspace =
        static_cast<size_t>(estimated * (kAdHocSafetyMultiplierPercent - 100) / 100);
    const bool has_runtime_workspace_estimator =
        level1_memory_estimate.has_value() &&
        level1_memory_estimate->runtime_workspace_bytes.has_value();
    const size_t runtime_transient_bytes =
        level1_memory_estimate.has_value() ? level1_memory_estimate->runtime_transient_bytes : 0;
    const size_t level1_workspace_bytes =
        std::max(level1_memory_estimate.has_value()
                     ? level1_memory_estimate->runtime_workspace_bytes.value_or(0)
                     : 0,
                 runtime_transient_bytes);
    const size_t selected_workspace =
        has_runtime_workspace_estimator
            ? level1_workspace_bytes
            : std::max(fallback_workspace, runtime_transient_bytes);
    const bool has_estimator =
        has_runtime_workspace_estimator || runtime_transient_bytes > fallback_workspace;
    const size_t persistent_prepack_bytes =
        level1_memory_estimate.has_value() ? level1_memory_estimate->persistent_prepack_bytes : 0;
    const size_t initialization_scratch_bytes =
        level1_memory_estimate.has_value() ? level1_memory_estimate->initialization_scratch_bytes : 0;
    pending_workspace_selection_by_node_.insert_or_assign(
        node.Index(),
        PendingWorkspaceEstimate{
            node.GetContainingGraph(),
            WorkspaceEstimateSelection{
                selected_workspace,
                has_estimator ? WorkspaceEstimateSource::kEstimator
                              : WorkspaceEstimateSource::kFallback,
                0,
                level1_workspace_bytes,
                persistent_prepack_bytes,
                initialization_scratch_bytes}});
    return static_cast<size_t>(estimated + selected_workspace +
                               persistent_prepack_bytes);
  }
 
  void ResetPendingResourcesImpl() override {
    pending_weights_.clear();
    pending_weights_by_node_.clear();
    pending_workspace_selection_by_node_.clear();
  }
 
  void CommitResourcesForNode(NodeIndex node_index) override {
    auto it = pending_weights_by_node_.find(node_index);
    if (it != pending_weights_by_node_.end()) {
      for (const auto& name : it->second) {
        pending_weights_.erase(name);
      }
      committed_weights_.insert(it->second.begin(), it->second.end());
      pending_weights_by_node_.erase(it);
    }
 
    auto workspace_it = pending_workspace_selection_by_node_.find(node_index);
    if (workspace_it != pending_workspace_selection_by_node_.end()) {
      CommitWorkspaceEstimate(
          workspace_it->second.graph_identity, node_index, workspace_it->second.selection);
      pending_workspace_selection_by_node_.erase(workspace_it);
    }
  }
 
  WorkspaceEstimateSelection GetPendingWorkspaceEstimateSelection(
      NodeIndex node_index) const override {
    auto it = pending_workspace_selection_by_node_.find(node_index);
    return it == pending_workspace_selection_by_node_.end() ? WorkspaceEstimateSelection{} : it->second.selection;
  }
 
  void AddCommittedWorkspaceEstimate(
      const void* graph_identity, size_t node_index,
      WorkspaceEstimateSelection selection) override {
    CommitWorkspaceEstimate(graph_identity, node_index, selection);
  }
 
  void ConsolidateCommittedWorkspaceReservations(
      const void* graph_identity, gsl::span<const size_t> source_node_indices,
      size_t destination_node_index) override {
    auto graph_it = committed_workspace_reservations_.find(graph_identity);
    if (graph_it == committed_workspace_reservations_.end()) {
      return;
    }
 
    ConsolidateWorkspaceReservations(graph_it->second, source_node_indices, destination_node_index);
  }
 
  WorkspaceEstimateSourceCounts GetWorkspaceEstimateSourceCounts() const override {
    return workspace_source_counts_;
  }
 
  WorkspaceEstimateComparisonSummary GetWorkspaceEstimateComparisonSummary() const override {
    return workspace_estimate_comparison_;
  }
 
  WorkspaceReservationMap GetCommittedWorkspaceReservations() const override {
    return committed_workspace_reservations_;
  }
 
  size_t GetCommittedWorkspaceEstimate() const override {
    return committed_workspace_estimate_;
  }
 
  size_t GetCommittedPersistentPrepackEstimate() const override {
    return committed_persistent_prepack_estimate_;
  }
 
  size_t GetCommittedInitializationScratchEstimate() const override {
    return committed_initialization_scratch_estimate_;
  }
 
 private:
  void CommitWorkspaceEstimate(
      const void* graph_identity, size_t node_index, WorkspaceEstimateSelection selection) {
    const size_t new_workspace_estimate =
        static_cast<size_t>(SafeInt<size_t>(committed_workspace_estimate_) + selection.bytes);
    const size_t new_persistent_prepack_estimate =
        static_cast<size_t>(SafeInt<size_t>(committed_persistent_prepack_estimate_) +
                            selection.persistent_prepack_bytes);
    // Kernel construction and PrePack() are sequential today, so committed
    // initialization scratch is a session-wide peak rather than a sum.
    const size_t new_initialization_scratch_estimate =
        std::max(committed_initialization_scratch_estimate_, selection.initialization_scratch_bytes);
 
    committed_workspace_estimate_ = new_workspace_estimate;
    committed_persistent_prepack_estimate_ = new_persistent_prepack_estimate;
    committed_initialization_scratch_estimate_ = new_initialization_scratch_estimate;
    committed_workspace_reservations_[graph_identity].insert_or_assign(node_index, selection);
    switch (selection.source) {
      case WorkspaceEstimateSource::kFallback:
        ++workspace_source_counts_.fallback;
        break;
      case WorkspaceEstimateSource::kProfile:
        ++workspace_source_counts_.profile;
        break;
      case WorkspaceEstimateSource::kEstimator:
        ++workspace_source_counts_.estimator;
        break;
      case WorkspaceEstimateSource::kProfileAndEstimator:
        ++workspace_source_counts_.profile_and_estimator;
        ++workspace_estimate_comparison_.node_count;
        workspace_estimate_comparison_.profiled_bytes =
            static_cast<size_t>(SafeInt<size_t>(workspace_estimate_comparison_.profiled_bytes) +
                                selection.profiled_bytes);
        workspace_estimate_comparison_.level1_estimated_bytes =
            static_cast<size_t>(SafeInt<size_t>(workspace_estimate_comparison_.level1_estimated_bytes) +
                                selection.level1_estimated_bytes);
        if (selection.profiled_bytes > selection.level1_estimated_bytes) {
          ++workspace_estimate_comparison_.profile_larger;
        } else if (selection.profiled_bytes < selection.level1_estimated_bytes) {
          ++workspace_estimate_comparison_.estimator_larger;
        } else {
          ++workspace_estimate_comparison_.equal;
        }
        break;
      case WorkspaceEstimateSource::kNone:
        break;
    }
  }
 
  size_t consumed_amount_ = 0;
  std::optional<InlinedHashMap<std::string, NodeAllocationStats>> node_stats_;
  // Weights committed from previous partitioning iterations.
  // These persist across GetCapability passes.
  InlinedHashSet<std::string> committed_weights_;
 
  // Initializers already counted during the current GetCapability pass. This
  // prevents a shared initializer from being charged to multiple probed nodes.
  InlinedHashSet<std::string> pending_weights_;
 
  // Initializers tentatively charged to each node. CommitResourcesForNode()
  // uses this mapping to move accepted-node initializers into committed_weights_.
  InlinedHashMap<NodeIndex, InlinedHashSet<std::string>> pending_weights_by_node_;
 
  // Selected workspace bytes and source for each probed node. Keeping them in
  // one value prevents the reported source from diverging from the selected size.
  InlinedHashMap<NodeIndex, PendingWorkspaceEstimate> pending_workspace_selection_by_node_;
 
  // Workspace total and source counts for nodes ultimately accepted by the EP.
  size_t committed_workspace_estimate_ = 0;
  size_t committed_persistent_prepack_estimate_ = 0;
  size_t committed_initialization_scratch_estimate_ = 0;
  WorkspaceEstimateSourceCounts workspace_source_counts_;
  WorkspaceEstimateComparisonSummary workspace_estimate_comparison_;
  WorkspaceReservationMap committed_workspace_reservations_;
};
 
struct NodeStatsRecorder::Impl {
  std::filesystem::path node_stats_path;
  // This is a node name to allocation stats map
  InlinedHashMap<std::string, NodeAllocationStats> node_stats;
  // Keeps track of nodes for which input/output sizes are accounted
  InlinedHashSet<std::string> input_output_accounted;
};
 
NodeStatsRecorder::NodeStatsRecorder(const std::filesystem::path& node_stats_path)
    : impl_(std::make_unique<Impl>()) {
  impl_->node_stats_path = node_stats_path;
}
 
NodeStatsRecorder::~NodeStatsRecorder() = default;
 
const std::filesystem::path& NodeStatsRecorder::GetNodeStatsFileName() const noexcept {
  return impl_->node_stats_path;
}
 
bool NodeStatsRecorder::ShouldAccountFor(const std::string& input_output_name) const {
  return impl_->input_output_accounted.insert(input_output_name).second;
}
 
void NodeStatsRecorder::ResetPerRunNameDeduper() {
  impl_->input_output_accounted.clear();
}
 
void NodeStatsRecorder::ReportNodeStats(const std::string& node_name, const NodeAllocationStats& stats) {
  auto result = impl_->node_stats.emplace(node_name, stats);
  if (!result.second) {
    // Node already exists, update the stats
    // This may happen when the user collects stats from multiple Runs()
    result.first->second.UpdateIfGreater(stats);
  }
}
 
void NodeStatsRecorder::DumpStats(std::ostream& os) const {
  os << "#name,input_sizes,initializers_sizes,total_dynamic_sizes,total_temp_allocations\n";
  for (const auto& [name, stats] : impl_->node_stats) {
    os << name << "," << stats.input_sizes << "," << stats.initializers_sizes << ","
       << stats.total_dynamic_sizes << ","
       << stats.total_temp_allocations << "\n";
  }
}
 
void NodeStatsRecorder::DumpStats(const std::filesystem::path& model_path) const {
  auto node_stats_file = model_path;
  if (node_stats_file.has_filename()) {
    node_stats_file = node_stats_file.parent_path();
  }
  node_stats_file /= GetNodeStatsFileName();
  std::ofstream ofs(node_stats_file, std::ofstream::out);
  ORT_ENFORCE(ofs.is_open(), "Failed to open file: ", node_stats_file);
  DumpStats(ofs);
  ofs.close();
}
 
static Status LoadNodeAllocationStats(
    const std::filesystem::path& model_path, const std::filesystem::path& file_name,
    InlinedHashMap<std::string, NodeAllocationStats>& result) {
  InlinedHashMap<std::string, NodeAllocationStats> node_stats;
  std::filesystem::path file_path = model_path;
  if (file_path.has_filename()) {
    file_path = file_path.parent_path();
  }
 
  file_path /= file_name;
 
  std::ifstream file(file_path);
  ORT_RETURN_IF_NOT(file.is_open(), "Failed to open file ", file_path);
  std::string line;
  // Read and load a CSV file line by line
  while (std::getline(file, line)) {
    if (line.empty() || line[0] == '#') continue;
 
    auto splits = utils::SplitString(line, ",", true);
    ORT_ENFORCE(splits.size() == 5, "Invalid line in the file ", file_path, ": ", line);
    if (splits[0].empty()) {
      continue;
    }
    std::string node_name{splits[0]};
    size_t input_sizes = SafeInt<size_t>(std::stoull(std::string{splits[1]}));
    size_t initializers_sizes = SafeInt<size_t>(std::stoull(std::string{splits[2]}));
    size_t total_dynamic_sizes = SafeInt<size_t>(std::stoull(std::string{splits[3]}));
    size_t total_temp_allocations = SafeInt<size_t>(std::stoull(std::string{splits[4]}));
    const NodeAllocationStats stats = {input_sizes, initializers_sizes, total_dynamic_sizes, total_temp_allocations};
    node_stats.insert_or_assign(std::move(node_name), stats);
  }
 
  result.swap(node_stats);
  return Status::OK();
}
 
Status CreateAccountants(
    const ConfigOptions& config_options,
    const std::filesystem::path& model_path,
    std::optional<ResourceAccountantMap>& acc_map) {
  WorkspaceEstimatorConfig estimator_config{
      config_options.GetConfigEntry(kOrtSessionOptionsCudaFpAIntBGemm),
      config_options.GetConfigEntry(kOrtSessionOptionsCudaFpAIntBProfileM)};
  if (const auto knob =
          config_options.GetConfigEntry(kOrtSessionOptionsCudaGqaWorkspaceMaxTotalSequenceLength);
      knob.has_value()) {
    auto& length = estimator_config.cuda_gqa_workspace_max_total_sequence_length;
    if (!TryParseStringWithClassicLocale(*knob, length) || length < 0) {
      return ORT_MAKE_STATUS(
          ONNXRUNTIME, INVALID_ARGUMENT,
          kOrtSessionOptionsCudaGqaWorkspaceMaxTotalSequenceLength,
          " must be a nonnegative decimal int64 value, but got: '", *knob, "'");
    }
  }
 
  std::optional<ResourceAccountantMap> result;
  // Check if CUDA partitioning settings are provided
  const std::string resource_partitioning_settings = config_options.GetConfigOrDefault(
      kOrtSessionOptionsResourceCudaPartitioningSettings, "");
 
  if (!resource_partitioning_settings.empty()) {
    auto splits = utils::SplitString(resource_partitioning_settings, ",", true);
    if (splits.size() == 2) {
      auto& map = result.emplace();
 
      std::optional<size_t> cuda_memory_limit;
      if (!splits[0].empty()) {
        cuda_memory_limit.emplace(0U);
        ORT_RETURN_IF_ERROR(ParseStringWithClassicLocale(std::string{splits[0]}, *cuda_memory_limit));
        cuda_memory_limit = SafeInt<size_t>(*cuda_memory_limit) * 1024;  // to bytes
      }
 
      std::optional<InlinedHashMap<std::string, NodeAllocationStats>> loaded_stats;
      if (!splits[1].empty()) {
        loaded_stats.emplace();
        ORT_RETURN_IF_ERROR(LoadNodeAllocationStats(model_path, splits[1], *loaded_stats));
      }
 
      if (cuda_memory_limit && loaded_stats) {
        map.insert_or_assign(kCudaExecutionProvider,
                             std::make_unique<SizeBasedResourceAccountant>(*cuda_memory_limit,
                                                                           std::move(*loaded_stats)));
      } else if (cuda_memory_limit) {
        map.insert_or_assign(kCudaExecutionProvider,
                             std::make_unique<SizeBasedResourceAccountant>(*cuda_memory_limit));
      } else if (loaded_stats) {
        map.insert_or_assign(kCudaExecutionProvider,
                             std::make_unique<SizeBasedResourceAccountant>(std::move(*loaded_stats)));
      } else {
        map.insert_or_assign(kCudaExecutionProvider, std::make_unique<SizeBasedResourceAccountant>());
      }
    } else {
      return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Invalid format for: ",
                             kOrtSessionOptionsResourceCudaPartitioningSettings,
                             " : expecting comma separated fields");
    }
  }
 
  if (result.has_value()) {
    for (auto& [ep_type, accountant] : *result) {
      ORT_UNUSED_PARAMETER(ep_type);
      accountant->SetWorkspaceEstimatorConfig(estimator_config);
    }
  }
 
  // Parse max shape overrides and attach to all accountants
  const std::string max_shape_config = config_options.GetConfigOrDefault(
      kOrtSessionOptionsMaxShapeOverride, "");
  if (!max_shape_config.empty() && result.has_value()) {
    MaxShapeOverrideMap shape_overrides;
    ORT_RETURN_IF_ERROR(ParseMaxShapeOverride(max_shape_config, shape_overrides));
    for (auto& [ep_type, accountant] : *result) {
      ORT_UNUSED_PARAMETER(ep_type);
      accountant->SetMaxShapeOverrides(shape_overrides);
    }
  }
 
  acc_map = std::move(result);
  return Status::OK();
}
 
std::string IResourceAccountant::MakeUniqueNodeName(const Node& node) {
  std::string result;
 
  uint32_t hash[4] = {0, 0, 0, 0};
  auto hash_str = [&hash](const std::string& str) {
    MurmurHash3::x86_128(str.data(), str.size(), hash[0], &hash);
  };
 
  const auto& node_name = (node.Name().empty()) ? node.OpType() : node.Name();
 
  for (const auto& def : node.InputDefs()) {
    hash_str(def->Name());
  }
 
  for (const auto& def : node.OutputDefs()) {
    hash_str(def->Name());
  }
 
  HashValue node_hash = hash[0] | (uint64_t(hash[1]) << 32);
  result.reserve(node_name.size() + 1 + 16);
  result.append(node_name).append("_").append(std::to_string(node_hash));
 
  return result;
}
 
ResourceCount AddResourceCounts(const ResourceCount& a, const ResourceCount& b) {
  return std::visit(
      [](auto lhs, auto rhs) -> ResourceCount {
        static_assert(std::is_same_v<decltype(lhs), decltype(rhs)>,
                      "AddResourceCounts requires both operands to hold the same type. "
                      "Handle the new ResourceCount variant member.");
        if constexpr (std::is_integral_v<decltype(lhs)>) {
          return static_cast<decltype(lhs)>(SafeInt<decltype(lhs)>(lhs) + rhs);
        } else {
          return lhs + rhs;
        }
      },
      a, b);
}
 
bool ResourceCountExceeds(const ResourceCount& a, const ResourceCount& b) {
  return std::visit(
      [](auto lhs, auto rhs) -> bool {
        static_assert(std::is_same_v<decltype(lhs), decltype(rhs)>,
                      "ResourceCountExceeds requires both operands to hold the same type. "
                      "Handle the new ResourceCount variant member.");
        return lhs > rhs;
      },
      a, b);
}
 
std::string FormatResourceCount(const ResourceCount& rc) {
  return std::visit(
      [](auto val) -> std::string { return std::to_string(val); },
      rc);
}
 
}  // namespace onnxruntime