Исходный код СУБД 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
#pragma once
 
#include <cstdint>
#include <filesystem>
#include <iosfwd>
#include <optional>
#include <string>
#include <unordered_set>
#include <variant>
 
#include <gsl/gsl>
 
#include "core/common/common.h"
#include "core/common/inlined_containers.h"
#include "core/framework/level1_memory_estimate.h"
#include "core/framework/max_shape_override.h"
 
namespace onnxruntime {
 
struct ConfigOptions;
#ifndef SHARED_PROVIDER
class Node;
#else
struct Node;
#endif
 
// Common holder for potentially different resource accounting
// for different EPs
using ResourceCount = std::variant<size_t>;
 
enum class WorkspaceEstimateSource {
  kNone,
  kFallback,
  kProfile,
  kEstimator,
  kProfileAndEstimator,
};
 
struct WorkspaceEstimateSelection {
  size_t bytes = 0;
  WorkspaceEstimateSource source = WorkspaceEstimateSource::kNone;
  size_t profiled_bytes = 0;
  size_t level1_estimated_bytes = 0;
  size_t persistent_prepack_bytes = 0;
  size_t initialization_scratch_bytes = 0;
};
 
struct WorkspaceEstimateSourceCounts {
  size_t fallback = 0;
  size_t profile = 0;
  size_t estimator = 0;
  size_t profile_and_estimator = 0;
};
 
struct WorkspaceEstimateComparisonSummary {
  size_t node_count = 0;
  size_t profile_larger = 0;
  size_t estimator_larger = 0;
  size_t equal = 0;
  size_t profiled_bytes = 0;
  size_t level1_estimated_bytes = 0;
};
 
struct WorkspaceEstimatorConfig {
  std::optional<std::string> cuda_fpa_intb_gemm;
  std::optional<std::string> cuda_fpa_intb_profile_m;
  // Validated nonnegative int64 envelope; zero means unspecified.
  // Reader-only until the GQA workspace estimator consumes the envelope.
  int64_t cuda_gqa_workspace_max_total_sequence_length = 0;
};
 
using NodeWorkspaceReservationMap = InlinedHashMap<size_t, WorkspaceEstimateSelection>;
using WorkspaceReservationMap = InlinedHashMap<const void*, NodeWorkspaceReservationMap>;
 
void ConsolidateWorkspaceReservations(
    NodeWorkspaceReservationMap& reservations,
    gsl::span<const size_t> source_node_indices,
    size_t destination_node_index);
 
// Type-erased arithmetic for ResourceCount values.
// Implementations use std::visit so the compiler enforces exhaustive handling
// of all variant members — adding a new type to ResourceCount will produce
// build errors at each call site that must be addressed.
//
// NOTE: These functions are NOT available through the provider bridge (shared library EPs).
// Budget enforcement for bridge-based EPs (e.g., in-tree CUDA EP) will be moved to the
// graph partitioner in a follow-up PR.
ResourceCount AddResourceCounts(const ResourceCount& a, const ResourceCount& b);
bool ResourceCountExceeds(const ResourceCount& a, const ResourceCount& b);
std::string FormatResourceCount(const ResourceCount& rc);
 
/// <summary>
/// This class is used for graph partitioning by EPs
/// It stores the cumulative amount of the resource such as
/// memory that would be consumed by the graph nodes if it is assigned to the EP.
///
/// It provides interfaces to add, remove and query the resource consumption.
///
/// Each provider may assign its own meaning to the resource according to its constraints.
/// </summary>
class IResourceAccountant {
 protected:
  IResourceAccountant() = default;
  IResourceAccountant(const ResourceCount& threshold) : threshold_(threshold) {}
 
 public:
  virtual ~IResourceAccountant() = default;
  virtual ResourceCount GetConsumedAmount() const = 0;
  virtual void AddConsumedAmount(const ResourceCount& amount) = 0;
  virtual void RemoveConsumedAmount(const ResourceCount& amount) = 0;
 
  // Computes the complete resource cost for a candidate node. A supplied
  // Level-1 estimate contributes prepack memory and uses its runtime workspace
  // instead of fallback workspace, or maximizes it with profiled workspace.
  virtual ResourceCount ComputeResourceCount(
      const Node& node, std::optional<Level1MemoryEstimate> level1_memory_estimate) = 0;
 
  ResourceCount ComputeResourceCount(const Node& node) {
    return ComputeResourceCount(node, std::nullopt);
  }
 
  std::optional<ResourceCount> GetThreshold() const {
    return threshold_;
  }
 
  void SetThreshold(const ResourceCount& threshold) {
    threshold_ = threshold;
  }
 
  void SetThreshold(std::optional<ResourceCount> threshold) {
    threshold_ = std::move(threshold);
  }
 
  void SetStopAssignment() noexcept {
    stop_assignment_ = true;
  }
 
  bool IsStopIssued() const noexcept { return stop_assignment_; }
 
  // Called before each GetCapability pass to reset per-pass state:
  // clears the stop flag (which only applies to the pass that set it)
  // and discards pending resource tracking from a previous (discarded) pass.
  void ResetForNewPass() {
    stop_assignment_ = false;
    ResetPendingResourcesImpl();
  }
 
  // Called when a node's cost is committed (AccountForNode/AccountForAllNodes).
  // Commits any per-node resource breakdown tracked while ComputeResourceCount()
  // was called. Default no-op for accountants without a resource breakdown.
  virtual void CommitResourcesForNode(size_t /*node_index*/) {}
 
  // Returns the pending workspace selection recorded while computing a node's cost.
  // Used when layout transformation defers committing first-pass capabilities.
  virtual WorkspaceEstimateSelection GetPendingWorkspaceEstimateSelection(
      size_t /*node_index*/) const {
    return {};
  }
 
  // Commits a workspace estimate whose original pending state is no longer available.
  // Used for nodes that survive a layout-transformation second pass.
  virtual void AddCommittedWorkspaceEstimate(
      const void* /*graph_identity*/, size_t /*node_index*/,
      WorkspaceEstimateSelection /*selection*/) {}
 
  // Consolidates committed reservations for constituent nodes onto their surviving fused node.
  virtual void ConsolidateCommittedWorkspaceReservations(
      const void* /*graph_identity*/, gsl::span<const size_t> /*source_node_indices*/,
      size_t /*destination_node_index*/) {}
 
  static std::string MakeUniqueNodeName(const Node& node);
 
  /// Set the max shape overrides for workspace estimation.
  /// Called during graph partitioner initialization when session.max_shape_override is set.
  void SetMaxShapeOverrides(MaxShapeOverrideMap overrides) {
    max_shape_overrides_ = std::move(overrides);
  }
 
  const MaxShapeOverrideMap& GetMaxShapeOverrides() const {
    return max_shape_overrides_;
  }
 
  void SetMaxShapeInferenceResult(MaxShapeInferenceResult result) {
    max_shape_inference_result_ = std::move(result);
  }
 
  const MaxShapeInferenceResult& GetMaxShapeInferenceResult() const {
    return max_shape_inference_result_;
  }
 
  void SetWorkspaceEstimatorConfig(WorkspaceEstimatorConfig config) {
    workspace_estimator_config_ = std::move(config);
  }
 
  const WorkspaceEstimatorConfig& GetWorkspaceEstimatorConfig() const {
    return workspace_estimator_config_;
  }
 
  /// Returns workspace for nodes that were accepted and committed by partitioning.
  virtual size_t GetCommittedWorkspaceEstimate() const { return 0; }
 
  /// Returns persistent prepack memory conservatively charged for accepted nodes.
  virtual size_t GetCommittedPersistentPrepackEstimate() const { return 0; }
 
  /// Returns the peak initialization scratch estimate across accepted nodes.
  /// This diagnostic is not included in the additive partitioning budget.
  virtual size_t GetCommittedInitializationScratchEstimate() const { return 0; }
 
  /// Returns accepted-node counts grouped by the workspace source used for budgeting.
  virtual WorkspaceEstimateSourceCounts GetWorkspaceEstimateSourceCounts() const { return {}; }
 
  /// Compares profile and estimator workspace values for accepted nodes where both were available.
  virtual WorkspaceEstimateComparisonSummary GetWorkspaceEstimateComparisonSummary() const { return {}; }
 
  /// Returns selected workspace reservations for accepted nodes, keyed by graph identity and node index.
  virtual WorkspaceReservationMap GetCommittedWorkspaceReservations() const { return {}; }
 
 protected:
  // Override to discard per-pass state for capabilities that were only probed.
  virtual void ResetPendingResourcesImpl() {}
 
 private:
  bool stop_assignment_ = false;
  std::optional<ResourceCount> threshold_;
  MaxShapeOverrideMap max_shape_overrides_;
  MaxShapeInferenceResult max_shape_inference_result_;
  WorkspaceEstimatorConfig workspace_estimator_config_;
};
 
// A map of Ep Type to a resource accountant for this EP
using ResourceAccountantMap = InlinedHashMap<std::string, std::unique_ptr<IResourceAccountant>>;
 
// This struct keeps accounting of the memory allocation stats
// for a kernel during runtime if enabled.
// Each metric describes max value seen as a result of inference run(s)
struct NodeAllocationStats {
  // Total input sizes for the node
  size_t input_sizes = 0;
  // consumed initializer sizes
  size_t initializers_sizes = 0;
  // dynamically allocated outputs that actually occurred
  // at inference time. (usually not fixed size and not pre-allocated)
  size_t total_dynamic_sizes = 0;
  // Temporary allocations that took place at this execution.
  size_t total_temp_allocations = 0;
 
  NodeAllocationStats& operator+=(const NodeAllocationStats& other) {
    input_sizes += other.input_sizes;
    initializers_sizes += other.initializers_sizes;
    total_dynamic_sizes += other.total_dynamic_sizes;
    total_temp_allocations += other.total_temp_allocations;
    return *this;
  }
 
  void UpdateIfGreater(const NodeAllocationStats& other) {
    input_sizes = std::max(input_sizes, other.input_sizes);
    initializers_sizes = std::max(initializers_sizes, other.initializers_sizes);
    total_dynamic_sizes = std::max(total_dynamic_sizes, other.total_dynamic_sizes);
    total_temp_allocations = std::max(total_temp_allocations, other.total_temp_allocations);
  }
};
 
class NodeStatsRecorder {
 public:
  explicit NodeStatsRecorder(const std::filesystem::path& stats_file_name);
  ~NodeStatsRecorder();
 
  ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(NodeStatsRecorder);
 
  const std::filesystem::path& GetNodeStatsFileName() const noexcept;
 
  bool ShouldAccountFor(const std::string& input_output_name) const;
 
  void ResetPerRunNameDeduper();
 
  void ReportNodeStats(const std::string& node_name, const NodeAllocationStats& stats);
 
  void DumpStats(const std::filesystem::path& model_path) const;
 
 private:
  void DumpStats(std::ostream& os) const;
 
  struct Impl;
  std::unique_ptr<Impl> impl_;
};
 
Status CreateAccountants(
    const ConfigOptions& config_options,
    const std::filesystem::path& model_path,
    std::optional<ResourceAccountantMap>& acc_map);
 
}  // namespace onnxruntime