Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-FileCopyrightText: Copyright 2024 Arm Limited and/or its affiliates <open-source-office@arm.com>
// Licensed under the MIT License.
#pragma once
 
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include "core/common/status.h"
#include "core/session/model_compilation_options.h"
#include "python/onnxruntime_pybind_state_common.h"
 
namespace onnxruntime {
class Environment;
 
namespace python {
#if !defined(ORT_MINIMAL_BUILD)
class PyEpContextData {
 public:
  PyEpContextData(const void* data, size_t size) : data_(data), size_(size) {}
 
  size_t Size() const noexcept { return size_; }
  pybind11::bytes Read(size_t offset, std::optional<size_t> length) const;
  void Invalidate() noexcept;
 
 private:
  const void* data_ = nullptr;
  size_t size_ = 0;
  bool valid_ = true;
};
 
class PyEpContextDataBuffer {
 public:
  PyEpContextDataBuffer(OrtAllocator* allocator, size_t max_data_size);
  ~PyEpContextDataBuffer();
 
  ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(PyEpContextDataBuffer);
 
  size_t Size() const noexcept { return size_; }
  size_t MaxSize() const noexcept { return max_data_size_; }
  bool IsAllocated() const noexcept { return allocated_; }
 
  void Allocate(size_t size);
  void Write(size_t offset, const pybind11::buffer& data);
  void Detach(void*& buffer, size_t& size);
  void Invalidate() noexcept;
 
 private:
  void ThrowIfInvalid() const;
 
  OrtAllocator* allocator_ = nullptr;
  const size_t max_data_size_;
  void* buffer_ = nullptr;
  size_t size_ = 0;
  bool allocated_ = false;
  bool valid_ = true;
};
 
using PyEpContextDataWriteFunc =
    std::function<void(const std::string&, const std::shared_ptr<PyEpContextData>&)>;
using PyEpContextDataReadFunc =
    std::function<void(const std::string&, const std::shared_ptr<PyEpContextDataBuffer>&)>;
 
struct PyEpContextDataReadRegistration {
  PyEpContextDataReadFunc read_func;
  size_t max_data_size;
};
 
OrtStatus* ORT_API_CALL PyEpContextDataReadFuncWrapper(void* state, const char* name, OrtAllocator* allocator,
                                                       void** buffer, size_t* data_size);
#endif  // !defined(ORT_MINIMAL_BUILD)
 
// Type of the function provided by Python code that is called by ORT to write out the compiled model.
using PyOutStreamWriteFunc = std::function<void(const pybind11::bytes& buffer)>;
 
// Type of the function provided by Python code that is called by ORT to handle every initializer.
using PyGetInitializerLocationFunc = std::function<std::shared_ptr<const OrtExternalInitializerInfo>(
    const std::string& initializer_name,
    const OrtValue& initializer_value,
    const OrtExternalInitializerInfo* external_info)>;
 
/// <summary>
/// Class exposed to Python that enables compiling ONNX models.
/// Internally wraps a onnxruntime::ModelCompilationOptions that stores and validates settings.
/// </summary>
class PyModelCompiler {
#if defined(ORT_MINIMAL_BUILD)
 public:
  bool not_defined_in_this_build{};  // Prevent empty class warning.
#else
 private:
  // private tag to pass to constructor to ensure that constructor cannot be directly called externally
  struct PrivateConstructorTag {};
 
 public:
  /// <summary>
  /// Static class function that creates a unique_ptr<PyModelCompiler> with the given settings.
  /// </summary>
  /// <param name="out">Output parameter for the result</param>
  /// <param name="env">The Environment instance</param>
  /// <param name="sess_options">The SessionOptions from which to initialize compilation options.</param>
  /// <param name="input_model_path_or_bytes">An r-value string that could be the input model's path or bytes</param>
  /// <param name="input_model_is_path">True if 'input_model_path_or_bytes' is a path, and false if its bytes.</param>
  /// <param name="embed_compiled_data_into_model">True to embed compiled binary data into EPContext nodes.</param>
  /// <param name="external_initializers_file_path">The file into which to store initializers for non-compiled
  /// nodes.</param>
  /// <param name="external_initializers_size_threshold">Ignored if 'external_initializers_file_path' is empty.
  /// Initializers with a size greater than this threshold are dumped into the external file.</param>
  /// <param name="flags">Flags from OrtCompileApiFlags</param>
  /// <param name="graph_opt_level">Optimization level for graph transformations on the model.
  /// Defaults to ORT_DISABLE_ALL to allow EP to get the original loaded model.</param>
  /// <param name="py_get_initializer_location_func">User's function to handle saving of initializers.</param>
  /// <returns>A Status indicating error or success.</returns>
  static onnxruntime::Status Create(/*out*/ std::unique_ptr<PyModelCompiler>& out,
                                    onnxruntime::Environment& env,
                                    const PySessionOptions& sess_options,
                                    std::string&& input_model_path_or_bytes, bool input_model_is_path,
                                    bool embed_compiled_data_into_model = false,
                                    const std::string& external_initializers_file_path = {},
                                    size_t external_initializers_size_threshold = 1024,
                                    uint32_t flags = 0,
                                    GraphOptimizationLevel graph_opt_level = GraphOptimizationLevel::ORT_DISABLE_ALL,
                                    const PyGetInitializerLocationFunc& py_get_initializer_location_func = nullptr);
 
  // Note: Creation should be done via Create(). This constructor is public so that it can be called from
  // std::make_shared().
  PyModelCompiler(onnxruntime::Environment& env, const OrtSessionOptions& sess_options,
                  std::shared_ptr<PyEpSelectionRegistration> py_ep_selection_registration,
                  std::shared_ptr<PyEpContextDataReadRegistration> py_ep_context_data_read_registration,
                  const PyGetInitializerLocationFunc& py_get_initializer_location_func,
                  PrivateConstructorTag);
 
  /// <summary>
  /// Compiles the input model and saves the result to an output file.
  /// If the 'output_model_path' is not specified,
  /// it is generated based on the input model's path by replacing '.onnx' with '_ctx.onnx'.
  /// </summary>
  /// <param name="output_model_path">The path into which to save the compiled model.</param>
  /// <returns>A Status indicating error or success.</returns>
  onnxruntime::Status CompileToFile(const std::string& output_model_path = {});
 
  /// <summary>
  /// Compiles the input model and stores the result into a buffer.
  /// </summary>
  /// <param name="output_buffer">A reference to the output buffer into which to store the
  /// serialized ONNX model bytes.</param>
  /// <returns>A Status indicating error or success.</returns>
  onnxruntime::Status CompileToBytes(std::string& output_buffer);
 
  /// <summary>
  /// Compiles the input model and writes the result into the provided output stream (write functor).
  /// </summary>
  /// <param name="write_func">Write functor that encapsulates the stream's state.</param>
  /// <returns>A Status indicating error or success.</returns>
  onnxruntime::Status CompileToOutStream(PyOutStreamWriteFunc& write_func);
 
  void SetEpContextDataWriteFunc(PyEpContextDataWriteFunc write_func);
  void ClearEpContextDataWriteFunc();
 
 private:
  onnxruntime::Status BeginCompilation();
  void EndCompilation() noexcept;
 
  onnxruntime::Environment& env_;
  std::shared_ptr<PyEpSelectionRegistration> py_ep_selection_registration_;
  std::shared_ptr<PyEpContextDataReadRegistration> py_ep_context_data_read_registration_;
  std::string input_model_bytes_;
  PyGetInitializerLocationFunc py_get_initializer_location_func_;
  PyEpContextDataWriteFunc py_ep_context_data_write_func_;
  onnxruntime::ModelCompilationOptions model_compile_options_;
  std::mutex compilation_mutex_;
  bool compilation_in_progress_{false};
#endif  // defined(ORT_MINIMAL_BUILD)
};
}  // namespace python
}  // namespace onnxruntime