Исходный код СУБД 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
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
#include <string>
#include <unordered_map>
 
#include "gtest/gtest.h"
#include "core/common/span_utils.h"
#include "core/graph/model.h"
#include "core/session/onnxruntime_cxx_api.h"
#include "test/framework/model_builder_utils.h"
#include "test/util/include/asserts.h"
#include "test/util/include/test_utils.h"
#include "test/util/include/inference_session_wrapper.h"
#include "test/test_environment.h"
 
using namespace ONNX_NAMESPACE;
 
extern std::unique_ptr<Ort::Env> ort_env;
 
namespace onnxruntime {
namespace test {
 
using namespace modelbuilder;
 
class ShapeInferenceTest : public ::testing::Test {
 protected:
  onnxruntime::Model model_;
  int node_count_;
  std::unordered_map<std::string, std::unique_ptr<onnxruntime::NodeArg>> name_to_arg_;
 
 public:
  ShapeInferenceTest() : model_("Test", false, DefaultLoggingManager().DefaultLogger()), node_count_(0) {}
 
  void Input(const std::string& name, const Type& type) {
    name_to_arg_[name] = std::make_unique<onnxruntime::NodeArg>(name, &type.value);
  }
 
  onnxruntime::NodeArg* Arg(const std::string& name) {
    if (name_to_arg_.count(name) == 0)
      name_to_arg_[name] = std::make_unique<onnxruntime::NodeArg>(name, nullptr);
    return name_to_arg_[name].get();
  }
 
  onnxruntime::Node& Node(const std::string& op, const std::string& input, const std::string& output) {
    std::vector<onnxruntime::NodeArg*> input_args({Arg(input)});
    std::vector<onnxruntime::NodeArg*> output_args({Arg(output)});
    int num = node_count_++;
    return model_.MainGraph().AddNode("node" + std::to_string(num), op, "test op", input_args, output_args);
  }
 
  void DoShapeInference() {
    auto status = model_.MainGraph().Resolve();
    EXPECT_TRUE(status.IsOK()) << "Graph resolve failed: " << status.ErrorMessage();
  }
 
  const TensorShapeProto* InputShape(onnxruntime::Node& node, int arg_num = 0) {
    return node.InputDefs()[arg_num]->Shape();
  }
 
  const TensorShapeProto* OutputShape(onnxruntime::Node& node, int arg_num = 0) {
    return node.OutputDefs()[arg_num]->Shape();
  }
 
};  // namespace test
 
TEST_F(ShapeInferenceTest, BasicTest) {
  Type type1({1, 50, 100});
  Input("X1", type1);
 
  auto& node = Node("Cast", "X1", "Y1");
  node.AddAttribute("to", int64_t{ONNX_NAMESPACE::TensorProto_DataType_INT32});
 
  DoShapeInference();
  // check inferred shapes
  Shape expected_shape({1, 50, 100});
  CheckShapeEquality(OutputShape(node), &expected_shape.value);
  CheckShapeEquality(InputShape(node), OutputShape(node));
}
 
TEST(ShapeInferenceDataPropagationTest, RejectsMalformedInitializerBeforeUnpacking) {
  Model model("malformed shape propagation initializer", false, ModelMetaData(), PathString(),
              IOnnxRuntimeOpSchemaRegistryList(), {{kOnnxDomain, 13}}, {},
              DefaultLoggingManager().DefaultLogger());
  Graph& graph = model.MainGraph();
 
  Type data_type({2, 3});
  auto& data = graph.GetOrCreateNodeArg("data", &data_type.value);
  auto& shape = graph.GetOrCreateNodeArg("shape", nullptr);
  auto& axes_arg = graph.GetOrCreateNodeArg("axes", nullptr);
  auto& output = graph.GetOrCreateNodeArg("output", nullptr);
 
  graph.SetInputs({&data});
  graph.SetOutputs({&output});
  graph.AddNode("shape", "Shape", "", {&data}, {&shape});
 
  TensorProto axes;
  axes.set_name("axes");
  axes.set_data_type(TensorProto_DataType_INT64);
  axes.add_dims(10000);
  axes.add_int64_data(0);
  graph.AddInitializedTensor(axes);
  graph.AddNode("unsqueeze", "Unsqueeze", "", {&shape, &axes_arg}, {&output});
 
  const auto status = graph.Resolve();
  ASSERT_FALSE(status.IsOK());
  EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("data field count (1) does not match expected count"));
}
 
TEST(ShapeInferenceDataPropagationTest, RejectsMalformedInitializerBeforeOnnxShapeInference) {
  Model model("malformed shape inference initializer", false, ModelMetaData(), PathString(),
              IOnnxRuntimeOpSchemaRegistryList(), {{kOnnxDomain, 13}}, {},
              DefaultLoggingManager().DefaultLogger());
  Graph& graph = model.MainGraph();
 
  Type data_type({2, 3});
  auto& data = graph.GetOrCreateNodeArg("data", &data_type.value);
  auto& shape_arg = graph.GetOrCreateNodeArg("shape", nullptr);
  auto& output = graph.GetOrCreateNodeArg("output", nullptr);
 
  graph.SetInputs({&data});
  graph.SetOutputs({&output});
 
  TensorProto shape;
  shape.set_name("shape");
  shape.set_data_type(TensorProto_DataType_INT64);
  shape.add_dims(2);
  shape.add_int64_data(6);
  graph.AddInitializedTensor(shape);
  graph.AddNode("reshape", "Reshape", "", {&data, &shape_arg}, {&output});
 
  const auto status = graph.Resolve();
  ASSERT_FALSE(status.IsOK());
  EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("data field count (1) does not match expected count"));
}
 
TEST(ShapeInferenceDataPropagationTest, RejectsMalformedGatherInitializerBeforeCustomPropagation) {
  Model model("malformed gather initializer", false, ModelMetaData(), PathString(),
              IOnnxRuntimeOpSchemaRegistryList(), {{kOnnxDomain, 13}}, {},
              DefaultLoggingManager().DefaultLogger());
  Graph& graph = model.MainGraph();
 
  Type data_type({2, 3});
  auto& data = graph.GetOrCreateNodeArg("data", &data_type.value);
  auto& shape = graph.GetOrCreateNodeArg("shape", nullptr);
  auto& indices_arg = graph.GetOrCreateNodeArg("indices", nullptr);
  auto& output = graph.GetOrCreateNodeArg("output", nullptr);
 
  graph.SetInputs({&data});
  graph.SetOutputs({&output});
  graph.AddNode("shape", "Shape", "", {&data}, {&shape});
 
  TensorProto indices;
  indices.set_name("indices");
  indices.set_data_type(TensorProto_DataType_INT64);
  indices.add_int64_data(0);
  indices.add_int64_data(1);
  graph.AddInitializedTensor(indices);
  graph.AddNode("gather", "Gather", "", {&shape, &indices_arg}, {&output});
 
  const auto status = graph.Resolve();
  ASSERT_FALSE(status.IsOK());
  EXPECT_THAT(status.ErrorMessage(), testing::HasSubstr("data field count (2) does not match expected count"));
}
 
TEST(ShapeInferenceV2Test, PartialDataPropagationTest) {
  {
    // Model #1
    // This model contains "Shape" and "Reshape" operators.
    auto model_path = ORT_TSTR("testdata/test_shape_data_propagation_with_shape_related_nodes.onnx");
 
    Ort::SessionOptions session_options{};
    session_options.SetGraphOptimizationLevel(ORT_DISABLE_ALL);
    session_options.AddFreeDimensionOverrideByName("batch", 1);
    session_options.AddFreeDimensionOverrideByName("width", 64);
    session_options.AddFreeDimensionOverrideByName("height", 64);
 
    // Even though all graph optimizations are disabled, the free dimension override is still enabled by default.
    // The shape of graph's output should be correctly inferred by shape inference and data propagation.
    Ort::Session session(*ort_env, model_path, session_options);
 
    // This graph only has one output
    ORT_ENFORCE(session.GetOutputCount() == 1);
 
    Ort::TypeInfo type_info = session.GetOutputTypeInfo(0);
    auto tensor_info = type_info.GetTensorTypeAndShapeInfo();
    std::vector<int64_t> output_shape = tensor_info.GetShape();
    EXPECT_TRUE(output_shape.size() == 4) << "The output shape should have 4 dimensions";
    EXPECT_TRUE(output_shape[0] == 1) << "The first dimension should have 1 as value";
    EXPECT_TRUE(output_shape[1] == 3) << "The second dimension should have 3 as value";
    EXPECT_TRUE(output_shape[2] == 64) << "The second dimension should have 64 as value";
    EXPECT_TRUE(output_shape[3] == 64) << "The second dimension should have 64 as value";
  }
 
  {
    // Model #2
    // This model contains "Shape", "Reshape", "Gather" and "Unsqueeze" operators.
    auto model_path = ORT_TSTR("testdata/test_shape_data_propagation_with_shape_related_nodes_v2.onnx");
 
    Ort::SessionOptions session_options{};
    session_options.SetGraphOptimizationLevel(ORT_DISABLE_ALL);
    session_options.AddFreeDimensionOverrideByName("batch", 1);
    session_options.AddFreeDimensionOverrideByName("width", 64);
    session_options.AddFreeDimensionOverrideByName("height", 64);
 
    // Even though all graph optimizations are disabled, the free dimension override is still enabled by default.
    // The shape of graph's output should be correctly inferred by shape inference and data propagation.
    Ort::Session session(*ort_env, model_path, session_options);
 
    // This graph only has one output
    ORT_ENFORCE(session.GetOutputCount() == 1);
 
    Ort::TypeInfo type_info = session.GetOutputTypeInfo(0);
    auto tensor_info = type_info.GetTensorTypeAndShapeInfo();
    std::vector<int64_t> output_shape = tensor_info.GetShape();
    EXPECT_TRUE(output_shape.size() == 3) << "The output shape should have 3 dimensions";
    EXPECT_TRUE(output_shape[0] == 1) << "The first dimension should have 1 as value";
    EXPECT_TRUE(output_shape[1] == 3) << "The second dimension should have 3 as value";
    EXPECT_TRUE(output_shape[2] == 4096) << "The second dimension should have 4096 as value";
  }
 
  {
    // Model #3
    // This model extends model #2 and appends Unsqueeze -> Unsqueeze -> Squeeze -> Squeeze -> Reshape to the end.
    auto model_path = ORT_TSTR("testdata/test_shape_data_propagation_with_shape_related_nodes_v3.onnx");
 
    Ort::SessionOptions session_options{};
    session_options.SetGraphOptimizationLevel(ORT_DISABLE_ALL);
    session_options.AddFreeDimensionOverrideByName("batch", 1);
    session_options.AddFreeDimensionOverrideByName("width", 64);
    session_options.AddFreeDimensionOverrideByName("height", 64);
 
    // Even though all graph optimizations are disabled, the free dimension override is still enabled by default.
    // The shape of graph's output should be correctly inferred by shape inference and data propagation.
    Ort::Session session(*ort_env, model_path, session_options);
 
    // This graph only has one output
    ORT_ENFORCE(session.GetOutputCount() == 1);
 
    Ort::TypeInfo type_info = session.GetOutputTypeInfo(0);
    auto tensor_info = type_info.GetTensorTypeAndShapeInfo();
    std::vector<int64_t> output_shape = tensor_info.GetShape();
    EXPECT_TRUE(output_shape.size() == 3) << "The output shape should have 3 dimensions";
    EXPECT_TRUE(output_shape[0] == 1) << "The first dimension should have 1 as value";
    EXPECT_TRUE(output_shape[1] == 3) << "The second dimension should have 3 as value";
    EXPECT_TRUE(output_shape[2] == 4096) << "The second dimension should have 4096 as value";
  }
 
  {
    // Model #4
    // This model contains Shape, Reshape, Squeeze, Range, ReduceSum.
    // It's from SoftmaxGrad_DefaultAxis test.
    auto model_path = ORT_TSTR("testdata/test_shape_data_propagation_with_shape_related_nodes_v4.onnx");
 
    Ort::SessionOptions session_options{};
    session_options.SetGraphOptimizationLevel(ORT_DISABLE_ALL);
 
    // Make sure it can load the model and run shape inference without errors.
    Ort::Session session(*ort_env, model_path, session_options);
  }
 
  {
    // Model #5
    // Regression test for the Shape -> Identity -> Unsqueeze path. ORT_ENABLE_BASIC removes the Identity,
    // then graph resolution re-runs data propagation after large initializers have been converted to
    // in-memory external OrtValues. The Unsqueeze axes initializer exercises the INT64 in-memory external path in
    // Graph::SaveShapeValuesFromDataPropagation.
    auto model_path = ORT_TSTR("testdata/test_shape_data_propagation_unsqueeze_inmemory_int64.onnx");
 
    Ort::SessionOptions session_options{};
    session_options.SetGraphOptimizationLevel(ORT_ENABLE_BASIC);
 
    Ort::Session session(*ort_env, model_path, session_options);
 
    ORT_ENFORCE(session.GetOutputCount() == 1);
  }
}
 
namespace {
struct MyCustomKernelWithOptionalInput {
  MyCustomKernelWithOptionalInput(const OrtKernelInfo* info) {
    Ort::ConstKernelInfo k_info(info);
 
    Ort::KeyValuePairs kvp = k_info.GetConfigEntries();
 
    EXPECT_NE(nullptr, kvp.GetValue("session.inter_op.allow_spinning"));
    EXPECT_STREQ("0", kvp.GetValue("session.inter_op.allow_spinning"));
 
    EXPECT_NE(nullptr, kvp.GetValue("session.intra_op.allow_spinning"));
    EXPECT_STREQ("0", kvp.GetValue("session.intra_op.allow_spinning"));
 
    EXPECT_EQ(nullptr, kvp.GetValue("__not__exist__"));
  }
 
  OrtStatusPtr ComputeV2(OrtKernelContext* /* context */) const {
    return nullptr;
  }
};
 
struct MyCustomOpWithOptionalInput : Ort::CustomOpBase<MyCustomOpWithOptionalInput,
                                                       MyCustomKernelWithOptionalInput,
                                                       true> {
  explicit MyCustomOpWithOptionalInput(const char* provider) : provider_(provider) {}
 
  OrtStatusPtr CreateKernelV2(const OrtApi& /* api */, const OrtKernelInfo* info, void** kernel) const {
    *kernel = new MyCustomKernelWithOptionalInput(info);
    return nullptr;
  };
 
  const char* GetName() const { return "FooBar"; };
  const char* GetExecutionProviderType() const { return provider_; };
 
  size_t GetInputTypeCount() const { return 3; };
  ONNXTensorElementDataType GetInputType(size_t /*index*/) const { return ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT; };
  OrtCustomOpInputOutputCharacteristic GetInputCharacteristic(size_t index) const {
    // The second input (index == 1) is optional
    if (index == 1)
      return OrtCustomOpInputOutputCharacteristic::INPUT_OUTPUT_OPTIONAL;
 
    return OrtCustomOpInputOutputCharacteristic::INPUT_OUTPUT_REQUIRED;
  }
 
  size_t GetOutputTypeCount() const { return 1; };
  ONNXTensorElementDataType GetOutputType(size_t /*index*/) const { return ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT; };
  OrtCustomOpInputOutputCharacteristic GetOutputCharacteristic(size_t /*index*/) const {
    return OrtCustomOpInputOutputCharacteristic::INPUT_OUTPUT_REQUIRED;
  }
 
 private:
  const char* provider_;
};
 
const ORTCHAR_T* const OPTIONAL_INPUT_CUSTOM_OP_MODEL_URI_2 = ORT_TSTR("testdata/foo_bar_2.onnx");
 
}  // namespace
 
// CustomOps Output type inference function quits if it
// encounters the an output that is optional and absent.
// It quits without any errors or logging. We want to make sure
// that inference proceeds for all of the outputs when absent optional inputs are present
TEST(ShapeInferenceCustomOpTest, custom_op_optional_input_inference_test) {
  MyCustomOpWithOptionalInput custom_op{onnxruntime::kCpuExecutionProvider};
  custom_op.InferOutputShapeFn = [](const OrtCustomOp* /*op*/, OrtShapeInferContext* /*ctx*/) -> OrtStatusPtr {
    return nullptr;
  };
 
  const auto& env = GetEnvironment();
 
  Ort::CustomOpDomain op_domain("test");
  op_domain.Add(&custom_op);
 
  std::initializer_list<OrtCustomOpDomain*> op_domains = {static_cast<OrtCustomOpDomain*>(op_domain)};
 
  SessionOptions sess_opts;
  sess_opts.inter_op_param.thread_pool_size = 1;
  sess_opts.intra_op_param.thread_pool_size = 1;
  ASSERT_STATUS_OK(sess_opts.config_options.AddConfigEntry("session.inter_op.allow_spinning", "0"));
  ASSERT_STATUS_OK(sess_opts.config_options.AddConfigEntry("session.intra_op.allow_spinning", "0"));
 
  InferenceSessionWrapper session{sess_opts, env, OPTIONAL_INPUT_CUSTOM_OP_MODEL_URI_2};
  ASSERT_STATUS_OK(session.AddCustomOpDomains(AsSpan(op_domains)));
 
  ASSERT_STATUS_OK(session.Load());
  ASSERT_STATUS_OK(session.Initialize());
 
  const onnxruntime::Model& model = session.GetModel();
  const auto& graph = model.MainGraph();
  const auto& nodes = graph.Nodes();
  for (const auto& node : nodes) {
    if (node.OpType() == "FooBar") {
      // check inferred shapes
      const auto* node_arg = node.OutputDefs()[0];
      const auto* type_proto = node_arg->TypeAsProto();
      ASSERT_NE(nullptr, type_proto);
      ASSERT_EQ(ONNX_NAMESPACE::TypeProto::ValueCase::kTensorType, type_proto->value_case());
      ASSERT_EQ(ONNX_NAMESPACE::TensorProto_DataType_FLOAT, type_proto->tensor_type().elem_type());
    }
  }
}
 
}  // namespace test
}  // namespace onnxruntime