Исходный код СУБД 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
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
#if !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)
 
#include "node_unit.h"
#include <utility>
#include "core/graph/graph_viewer.h"
 
namespace onnxruntime {
 
namespace {
 
enum class QLinearOpType : uint8_t {
  Unknown,  // Unknown or not a linear quantized op
  DequantizeLinear,
  QuantizeLinear,
  QLinearConv,
  QLinearMatMul,
  QLinearAdd,
  QLinearSigmoid,
  QLinearAveragePool,
  QLinearMul,
  QLinearReduceMean,
  QLinearConcat,
  QLinearGlobalAveragePool,
  QLinearLeakyRelu,
};
 
QLinearOpType GetQLinearOpType(const onnxruntime::Node& node) {
  const auto& op_type = node.OpType();
  if (op_type == "DequantizeLinear")
    return QLinearOpType::DequantizeLinear;
  else if (op_type == "QuantizeLinear")
    return QLinearOpType::QuantizeLinear;
  else if (op_type == "QLinearConv")
    return QLinearOpType::QLinearConv;
  else if (op_type == "QLinearMatMul")
    return QLinearOpType::QLinearMatMul;
  else if (op_type == "QLinearAdd")
    return QLinearOpType::QLinearAdd;
  else if (op_type == "QLinearSigmoid")
    return QLinearOpType::QLinearSigmoid;
  else if (op_type == "QLinearAveragePool")
    return QLinearOpType::QLinearAveragePool;
  else if (op_type == "QLinearMul")
    return QLinearOpType::QLinearMul;
  else if (op_type == "QLinearReduceMean")
    return QLinearOpType::QLinearReduceMean;
  else if (op_type == "QLinearConcat")
    return QLinearOpType::QLinearConcat;
  else if (op_type == "QLinearGlobalAveragePool")
    return QLinearOpType::QLinearGlobalAveragePool;
  else if (op_type == "QLinearLeakyRelu")
    return QLinearOpType::QLinearLeakyRelu;
 
  return QLinearOpType::Unknown;
}
 
// Ops have 1 input
bool IsUnaryQLinearOp(QLinearOpType type) {
  return type == QLinearOpType::QLinearSigmoid ||
         type == QLinearOpType::QLinearAveragePool ||
         type == QLinearOpType::QLinearGlobalAveragePool ||
         type == QLinearOpType::QLinearLeakyRelu ||
         type == QLinearOpType::QLinearReduceMean;
}
 
// Ops have 2 inputs
bool IsBinaryQLinearOp(QLinearOpType type) {
  return type == QLinearOpType::QLinearConv ||
         type == QLinearOpType::QLinearMatMul ||
         type == QLinearOpType::QLinearAdd ||
         type == QLinearOpType::QLinearMul;
}
 
// Ops have 1 or more inputs
bool IsVariadicQLinearOp(QLinearOpType type) {
  return type == QLinearOpType::QLinearConcat;
}
 
const std::vector<const Node*> GetQDQIONodes(const GraphViewer& graph_viewer,
                                             const QDQ::NodeGroup& node_group, bool is_input) {
  std::vector<const Node*> io_nodes;
  const auto& src_nodes = is_input ? node_group.dq_nodes : node_group.q_nodes;
  io_nodes.reserve(src_nodes.size());
  for (const auto& node_idx : src_nodes) {
    io_nodes.push_back(graph_viewer.GetNode(node_idx));
  }
 
  return io_nodes;
}
 
// Get the input or output NodeUnitIODef(s) for the given QDQ NodeGroup
std::vector<NodeUnitIODef> GetQDQIODefs(const Node& target_node, const QDQ::NodeGroup& node_group, bool is_input) {
  const auto& dq_or_q_nodes = is_input ? node_group.dq_nodes : node_group.q_nodes;
  const auto target_node_io_defs = is_input ? target_node.InputDefs() : target_node.OutputDefs();
  const size_t target_node_io_defs_size = target_node_io_defs.size();
 
  // Find all the quantized IO defs and indices (for the input/output of the target node)
  std::unordered_map<size_t, NodeUnitIODef> quantized_io_defs;
  quantized_io_defs.reserve(target_node_io_defs_size);
 
  auto cur = is_input ? target_node.InputEdgesBegin() : target_node.OutputEdgesBegin();
  auto end = is_input ? target_node.InputEdgesEnd() : target_node.OutputEdgesEnd();
 
  for (; cur != end; ++cur) {
    const Node& node = cur->GetNode();
 
    // If we can find the node index in the dq or q nodes this is a quantized input/output
    if (std::find(dq_or_q_nodes.cbegin(), dq_or_q_nodes.cend(), node.Index()) != dq_or_q_nodes.cend()) {
      const auto node_inputs = node.InputDefs();
      const auto& node_attrs = node.GetAttributes();
 
      // Get the Q or DQ axis attribute if available.
      std::optional<int64_t> axis;
      if (auto entry = node_attrs.find("axis"); entry != node_attrs.end()) {
        axis = entry->second.i();
      }
 
      // quantization scale and zp are always the input[1, 2]
      NodeUnitIODef::QuantParam quant_param{*node_inputs[1], node_inputs.size() == 3 ? node_inputs[2] : nullptr, axis};
 
      if (is_input) {
        // DQ is input to the target node, use the DstArgIndex
        auto idx = cur->GetDstArgIndex();
        // This is a DQ node, we are using x, x_scale, x_zp (input[0, 1, 2])
        quantized_io_defs.insert({idx, NodeUnitIODef{*node_inputs[0], quant_param}});
      } else {
        // Q is output of the target node, use the SrcArgIndex
        auto idx = cur->GetSrcArgIndex();
        // This is a Q node, we are using y (output[0]), y_scale, y_zp (input[1, 2])
        const auto node_outputs = node.OutputDefs();
        quantized_io_defs.insert({idx, NodeUnitIODef{*node_outputs[0], quant_param}});
      }
    }
  }
 
  // Construct the IODefs for this QDQ NodeGroup
  std::vector<NodeUnitIODef> io_defs;
  io_defs.reserve(target_node_io_defs_size);
  for (size_t i = 0; i < target_node_io_defs_size; i++) {
    // If we can find the NodeUnitIODef for this index, this is a quantized input/output
    if (quantized_io_defs.find(i) != quantized_io_defs.cend()) {
      io_defs.push_back(std::move(quantized_io_defs.at(i)));
    } else {
      // This is a regular input
      io_defs.push_back({*target_node_io_defs[i], std::nullopt});
    }
  }
 
  return io_defs;
}
 
}  // namespace
 
Status QDQ::NodeGroup::CanCreateNodeGroup(const GraphViewer& graph_viewer,
                                          const Node& target_node,
                                          const Node* redundant_clip_node,
                                          gsl::span<const Node* const> dq_nodes,
                                          gsl::span<const Node* const> q_nodes) {
  // Within a QDQ node group, a target node input is the only consumer of each DQ.
  // This should have been ensured by the EnsureUniqueDQForNodeUnit graph transformer, but other graph modifications
  // may have happened since. Verify that this is still true.
  for (const auto* dq_node : dq_nodes) {
    const bool dq_produces_graph_output = graph_viewer.NodeProducesGraphOutput(*dq_node);
    ORT_RETURN_IF(dq_produces_graph_output,
                  "QDQ node group cannot have DQ node that produces a graph output. DQ node: ", dq_node->Name(),
                  ", target node: ", target_node.Name());
 
    const bool dq_has_single_output_edge_to_target =
        dq_node->GetOutputEdgesCount() == 1 &&
        dq_node->OutputEdgesBegin()->GetNode().Index() == target_node.Index();
    ORT_RETURN_IF_NOT(dq_has_single_output_edge_to_target,
                      "QDQ node group cannot have DQ that doesn't have a single output edge to the target node. "
                      "DQ node: ",
                      dq_node->Name(), ", target node: ", target_node.Name());
  }
 
  // If redundant_clip_node is present, currently we require target node has only one output edge, which is connected to
  // the redundant_clip_node. The redundant_clip_node's output is consumed by the Q node that can be fused with itself.
  if (redundant_clip_node) {
    ORT_RETURN_IF_NOT(!graph_viewer.NodeProducesGraphOutput(target_node) && target_node.GetOutputEdgesCount() == 1 &&
                          target_node.OutputEdgesBegin()->GetNode().Index() == redundant_clip_node->Index(),
                      "QDQ node group cannot have target node with more than one output edge if there is redunant clip "
                      "node. target node: ",
                      target_node.Name());
    ORT_RETURN_IF_NOT(
        !graph_viewer.NodeProducesGraphOutput(*redundant_clip_node) && q_nodes.size() == 1 &&
            redundant_clip_node->GetOutputEdgesCount() == 1 &&
            redundant_clip_node->OutputEdgesBegin()->GetNode().Index() == q_nodes[0]->Index(),
        "QDQ node group cannot have redudant clip node that doesn't have a single output edge to a Q node. "
        "redundant clip node: ",
        redundant_clip_node->Name());
    return Status::OK();
  }
 
  // an output from the target node can have either Q consumers or direct consumers. it cannot have both.
  // this must be checked on a per output basis.
  // e.g. TopK produces values and indices. The indices output won't be quantized, so even if we replace the TopK QDQ
  // node group with a quantized TopK, an int64_t indices value will be produced and can provide a graph output.
  if (!q_nodes.empty()) {
    auto cur_edge = target_node.OutputEdgesBegin();
    auto end_edge = target_node.OutputEdgesEnd();
    std::vector<const Node*> output_consumers(target_node.OutputDefs().size(), nullptr);
 
    for (; cur_edge != end_edge; ++cur_edge) {
      auto output_idx = cur_edge->GetSrcArgIndex();
      const Node& this_consumer = cur_edge->GetNode();
      const Node* existing_consumer = output_consumers[output_idx];
 
      if (existing_consumer != nullptr) {
        // another edge for this output. either both are Q or both are not.
        bool valid = true;
        if (existing_consumer->OpType() == "QuantizeLinear") {
          valid = this_consumer.OpType() == "QuantizeLinear";
        } else {
          valid = this_consumer.OpType() != "QuantizeLinear";
        }
 
        ORT_RETURN_IF_NOT(valid,
                          "QDQ node group cannot have an output from the target node being consumed by a Q node and "
                          "a non-Q node. target node: ",
                          target_node.Name());
      } else {
        output_consumers[output_idx] = &this_consumer;
      }
    }
 
    const auto& graph_outputs = graph_viewer.GetOutputs();
    for (size_t idx = 0, end = output_consumers.size(); idx < end; ++idx) {
      // any output with a Q cannot be a graph output as it will disappear if the QDQ node unit is converted to
      // a quantized op.
      if (output_consumers[idx] != nullptr && output_consumers[idx]->OpType() == "QuantizeLinear") {
        const auto& output_name = target_node.OutputDefs()[idx]->Name();
        bool is_graph_output = std::any_of(graph_outputs.begin(), graph_outputs.end(),
                                           [&output_name](const NodeArg* node_arg) {
                                             return node_arg->Name() == output_name;
                                           });
        ORT_RETURN_IF(is_graph_output,
                      "QDQ node group cannot have an output from the target node that is consumed by a Q node and "
                      "a graph output. target node: ",
                      target_node.Name(), " output idx:", idx);
      }
    }
  }
 
  return Status::OK();
}
 
NodeUnit::NodeUnit(const Node& node)
    : target_node_(node),
      redundant_clip_node_(nullptr),
      type_(Type::SingleNode),
      input_edge_count_(node.GetInputEdgesCount()) {
  InitForSingleNode();
}
 
NodeUnit::NodeUnit(const GraphViewer& graph_viewer, const QDQ::NodeGroup& node_group)
    : dq_nodes_{GetQDQIONodes(graph_viewer, node_group, true /* is_input */)},
      target_node_(*graph_viewer.GetNode(node_group.target_node)),
      redundant_clip_node_(node_group.redundant_clip_node.has_value()
                               ? graph_viewer.GetNode(node_group.redundant_clip_node.value())
                               : nullptr),
      q_nodes_{GetQDQIONodes(graph_viewer, node_group, false /* is_input */)},
      type_(Type::QDQGroup),
      inputs_{GetQDQIODefs(target_node_, node_group, true /* is_input */)},
      outputs_{GetQDQIODefs((redundant_clip_node_ ? *redundant_clip_node_ : target_node_), node_group,
                            false /* is_input */)} {
  ORT_THROW_IF_ERROR(
      QDQ::NodeGroup::CanCreateNodeGroup(graph_viewer, target_node_, redundant_clip_node_, dq_nodes_, q_nodes_));
 
  input_edge_count_ = std::accumulate(dq_nodes_.cbegin(), dq_nodes_.cend(), size_t(0),
                                      [](size_t acc, const Node* node) { return acc + node->GetInputEdgesCount(); });
 
  // add edges for inputs that are not from DQ nodes. there is one edge to each DQ node.
  // other inputs could come from initializers or graph inputs (no edges) or other nodes (edge).
  input_edge_count_ += target_node_.GetInputEdgesCount() - dq_nodes_.size();
 
  // create output edges. each target node output either goes to Q node/s or non-Q node/s.
  // ValidateNodeGroupQDQNodes ensures this.
  // If redundant clip node is present, the target node has only one output edge to the redundant clip node.
  const Node& output_producer = redundant_clip_node_ ? *redundant_clip_node_ : target_node_;
  auto cur_edge = output_producer.OutputEdgesBegin();
  auto end_edge = output_producer.OutputEdgesEnd();
  for (; cur_edge != end_edge; ++cur_edge) {
    const Node& node = cur_edge->GetNode();
 
    // if node is in q_nodes we hide the Q node.
    if (std::find(q_nodes_.cbegin(), q_nodes_.cend(), &node) != q_nodes_.cend()) {
      auto src_idx = cur_edge->GetSrcArgIndex();
      auto q_cur_edge = node.OutputEdgesBegin();
      auto q_end_edge = node.OutputEdgesEnd();
      for (; q_cur_edge != q_end_edge; ++q_cur_edge) {
        output_edges_.insert(Node::EdgeEnd{q_cur_edge->GetNode(), src_idx, q_cur_edge->GetDstArgIndex()});
      }
    } else {
      // non-Q node, or Q node that isn't in the QDQ node group (unexpected but may be possible). add as-is.
      output_edges_.insert(*cur_edge);
    }
  }
}
 
NodeUnit::NodeUnit(gsl::span<const Node* const> dq_nodes, const Node& target_node, const Node* redundant_clip_node,
                   gsl::span<const Node* const> q_nodes, Type unit_type,
                   gsl::span<const NodeUnitIODef> inputs, gsl::span<const NodeUnitIODef> outputs,
                   size_t input_edge_count, Node::EdgeSet output_edges)
    : dq_nodes_(dq_nodes.begin(), dq_nodes.end()),
      target_node_(target_node),
      redundant_clip_node_(redundant_clip_node),
      q_nodes_(q_nodes.begin(), q_nodes.end()),
      type_(unit_type),
      inputs_(inputs.begin(), inputs.end()),
      outputs_(outputs.begin(), outputs.end()),
      input_edge_count_(input_edge_count),
      output_edges_(std::move(output_edges)) {
}
 
const std::string& NodeUnit::Domain() const noexcept { return target_node_.Domain(); }
const std::string& NodeUnit::OpType() const noexcept { return target_node_.OpType(); }
const std::string& NodeUnit::Name() const noexcept { return target_node_.Name(); }
int NodeUnit::SinceVersion() const noexcept { return target_node_.SinceVersion(); }
NodeIndex NodeUnit::Index() const noexcept { return target_node_.Index(); }
const std::filesystem::path& NodeUnit::ModelPath() const noexcept { return target_node_.ModelPath(); }
ProviderType NodeUnit::GetExecutionProviderType() const noexcept { return target_node_.GetExecutionProviderType(); }
 
void NodeUnit::InitForSingleNode() {
  const auto& input_defs = target_node_.InputDefs();
  const auto& output_defs = target_node_.OutputDefs();
  const auto& node_attrs = target_node_.GetAttributes();
  auto qlinear_type = GetQLinearOpType(target_node_);
  if (qlinear_type == QLinearOpType::Unknown) {
    // Not a Qlinear op, add all inputs / outputs
    auto add_all_io = [](std::vector<NodeUnitIODef>& defs,
                         const ConstPointerContainer<std::vector<NodeArg*>>& node_defs) {
      defs.reserve(node_defs.size());
 
      for (const auto def : node_defs) {
        defs.push_back(NodeUnitIODef{*def, std::nullopt});
      }
    };
 
    add_all_io(inputs_, input_defs);
    add_all_io(outputs_, output_defs);
  } else if (IsUnaryQLinearOp(qlinear_type)) {
    // Unary QLinear Op has 5 inputs
    // x, x_scale, x_zp, y_scale, y_zp (optional)
    inputs_.push_back(NodeUnitIODef{*input_defs[0], NodeUnitIODef::QuantParam{*input_defs[1], input_defs[2]}});
    outputs_.push_back(NodeUnitIODef{*output_defs[0],
                                     NodeUnitIODef::QuantParam{*input_defs[3],
                                                               input_defs.size() > 4 ? input_defs[4] : nullptr}});
 
  } else if (IsBinaryQLinearOp(qlinear_type)) {
    // Binary QLinear Op has 9 inputs
    // x1, x1_scale, x1_zp, x2/w, x2_scale, x2_zp, y_scale , y_zp, B
    inputs_.push_back(NodeUnitIODef{*input_defs[0], NodeUnitIODef::QuantParam{*input_defs[1], input_defs[2]}});
    inputs_.push_back(NodeUnitIODef{*input_defs[3], NodeUnitIODef::QuantParam{*input_defs[4], input_defs[5]}});
 
    if (input_defs.size() == 9) {                                      // has Bias
      inputs_.push_back(NodeUnitIODef{*input_defs[8], std::nullopt});  // for Bias the scale and zp are optional
    }
 
    outputs_.push_back(NodeUnitIODef{*output_defs[0], NodeUnitIODef::QuantParam{*input_defs[6], input_defs[7]}});
 
  } else if (qlinear_type == QLinearOpType::DequantizeLinear) {
    // DequantizeLinear has 3 inputs
    // x, x_scale, x_zp
    // output is not quantized
 
    // Get the DQ axis attribute if available.
    std::optional<int64_t> axis;
    if (auto entry = node_attrs.find("axis"); entry != node_attrs.end()) {
      axis = entry->second.i();
    }
 
    inputs_.push_back(NodeUnitIODef{*input_defs[0],
                                    NodeUnitIODef::QuantParam{*input_defs[1],
                                                              input_defs.size() == 3 ? input_defs[2] : nullptr,
                                                              axis}});
    outputs_.push_back(NodeUnitIODef{*output_defs[0], std::nullopt});
 
  } else if (qlinear_type == QLinearOpType::QuantizeLinear) {
    // QuantizeLinear the input is not quantized and has 3 inputs
    // x, y_scale, y_zp (optional)
    // The output is quantized
 
    // Get the Q axis attribute if available.
    std::optional<int64_t> axis;
    if (auto entry = node_attrs.find("axis"); entry != node_attrs.end()) {
      axis = entry->second.i();
    }
 
    inputs_.push_back(NodeUnitIODef{*input_defs[0], std::nullopt});
    outputs_.push_back(NodeUnitIODef{*output_defs[0],
                                     NodeUnitIODef::QuantParam{*input_defs[1],
                                                               input_defs.size() == 3 ? input_defs[2] : nullptr,
                                                               axis}});
  } else if (IsVariadicQLinearOp(qlinear_type)) {
    size_t input_num = (input_defs.size() - 2) / 3;
    for (size_t i = 0; i < input_num; i++) {
      inputs_.push_back(NodeUnitIODef{*input_defs[3 * i + 2], NodeUnitIODef::QuantParam{*input_defs[3 * i + 3],
                                                                                        input_defs[3 * i + 4]}});
    }
    outputs_.push_back(NodeUnitIODef{*output_defs[0], NodeUnitIODef::QuantParam{*input_defs[0], input_defs[1]}});
  } else {
    ORT_THROW("The QLinear op [", static_cast<uint8_t>(qlinear_type), "] is not supported");
  }
}
 
Node::EdgeConstIterator NodeUnit::OutputEdgesBegin() const {
  return (type_ == Type::SingleNode) ? target_node_.OutputEdgesBegin() : output_edges_.begin();
}
 
Node::EdgeConstIterator NodeUnit::OutputEdgesEnd() const {
  return (type_ == Type::SingleNode) ? target_node_.OutputEdgesEnd() : output_edges_.end();
}
 
std::vector<const Node*> NodeUnit::GetAllNodesInGroup() const noexcept {
  std::vector<const Node*> all_nodes = dq_nodes_;
  all_nodes.push_back(&target_node_);
  if (redundant_clip_node_) {
    all_nodes.push_back(redundant_clip_node_);
  }
  all_nodes.reserve(all_nodes.size() + q_nodes_.size());
  for (auto& n : q_nodes_)
    all_nodes.push_back(n);
  return all_nodes;
}
 
}  // namespace onnxruntime
 
#endif  // !defined(ORT_MINIMAL_BUILD) || defined(ORT_EXTENDED_MINIMAL_BUILD)