summaryrefslogtreecommitdiff
path: root/compiler/mir/src/mir_onnx_importer/ONNXImporterImpl.cpp
blob: 6379b6c87d637882b96ca4750d0451c8aa6dc9ab (plain)
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
/*
 * Copyright (c) 2018 Samsung Electronics Co., Ltd. All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ONNXImporterImpl.h"
#include "ONNXHelpers.h"
#include "ONNXOpRegistration.h"
#include "onnx/onnx.pb.h"

#include "mir/Shape.h"
#include "mir/TensorUtil.h"

#include "mir/ops/ConstantOp.h"

#include <fcntl.h>

#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/text_format.h>
#include <functional>
#include <iostream>
#include <memory>
#include <utility>

namespace mir_onnx
{

namespace
{

class ONNXImporterImpl final
{
public:
  ONNXImporterImpl();
  ~ONNXImporterImpl();
  /// @brief Load the model and convert it into a MIR Graph.
  std::unique_ptr<mir::Graph> importModelFromBinaryFile(const std::string &filename);
  std::unique_ptr<mir::Graph> importModelFromTextFile(const std::string &filename);

private:
  std::unique_ptr<mir::Graph> createIR();
  void createGraphInputs();
  void collectUnsupportedOps();
  std::unique_ptr<onnx::ModelProto> _model;
  std::unique_ptr<ConverterContext> _converterCtx;
  std::unique_ptr<ModelContext> _modelCtx;
  std::unique_ptr<mir::Graph> _graph;
};

ONNXImporterImpl::ONNXImporterImpl() { registerSupportedOps(); }

ONNXImporterImpl::~ONNXImporterImpl() = default;

void loadModelFromBinaryFile(const std::string &filename, onnx::ModelProto *model)
{
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  int file_handle = open(filename.c_str(), O_RDONLY);

  if (file_handle == -1)
    throw std::runtime_error("Couldn't open file \"" + filename + "\": " + std::strerror(errno) +
                             ".");

  google::protobuf::io::FileInputStream file_stream(file_handle);
  file_stream.SetCloseOnDelete(true);

  google::protobuf::io::CodedInputStream coded_stream(&file_stream);
  coded_stream.SetTotalBytesLimit(INT_MAX, INT_MAX);

  if (!model->ParseFromCodedStream(&coded_stream))
    throw std::runtime_error("Couldn't parse file \"" + filename + "\".");

  // If the file has not been consumed entirely, assume that the file is in the wrong format.
  if (!coded_stream.ConsumedEntireMessage())
    throw std::runtime_error("File \"" + filename + "\" has not been consumed entirely.");
}

void loadModelFromTextFile(const std::string &filename, onnx::ModelProto *model)
{
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  int file_handle = open(filename.c_str(), O_RDONLY);

  if (file_handle == -1)
    throw std::runtime_error("Couldn't open file \"" + filename + "\": " + std::strerror(errno) +
                             ".");

  google::protobuf::io::FileInputStream file_stream(file_handle);
  file_stream.SetCloseOnDelete(true);

  if (!google::protobuf::TextFormat::Parse(&file_stream, model))
    throw std::runtime_error("Couldn't parse file \"" + filename + "\".");
}

std::unique_ptr<mir::Graph> ONNXImporterImpl::importModelFromBinaryFile(const std::string &filename)
{
  _model = std::make_unique<onnx::ModelProto>();
  loadModelFromBinaryFile(filename, _model.get());
  _modelCtx = std::make_unique<ModelContext>(_model.get());
  collectUnsupportedOps();
  return createIR();
}

std::unique_ptr<mir::Graph> ONNXImporterImpl::importModelFromTextFile(const std::string &filename)
{
  _model = std::make_unique<onnx::ModelProto>();
  loadModelFromTextFile(filename, _model.get());
  _modelCtx = std::make_unique<ModelContext>(_model.get());
  collectUnsupportedOps();
  return createIR();
}

void ONNXImporterImpl::collectUnsupportedOps()
{
  std::set<std::pair<std::string, int64_t>> problems_op_set;

  for (int i = 0; i < _model->graph().node_size(); i++)
  {
    const auto &onnx_node = _model->graph().node(i);
    assert(onnx_node.has_op_type());
    const auto &op_type = onnx_node.op_type();
    auto opset = _modelCtx->getDomainOpsetVersion(onnx_node.domain());

    NodeConverterRegistry::ConverterFunc converter =
      NodeConverterRegistry::getInstance().lookup(op_type, opset);

    if (converter == nullptr)
      problems_op_set.emplace(op_type, opset);
  }
  if (!problems_op_set.empty())
  {
    std::cerr << "The following operators are not supported:\n";
    for (const auto &op : problems_op_set)
      std::cerr << op.first << " opset " << op.second << std::endl;
    throw std::runtime_error("Unsupported operators found");
  }
}

void ONNXImporterImpl::createGraphInputs()
{
  const auto &graph = _model->graph();
  const auto &initializer = graph.initializer();

  // Create all initializer Tensors
  for (const auto &tensor : initializer)
  {
    const auto mir_tensor = createTensor(&tensor);
    auto *op = _graph->create<mir::ops::ConstantOp>(mir_tensor);
    _converterCtx->setOutput(tensor.name(), op->getOutput(0));
  }

  for (const auto &input : graph.input())
  {
    assert(input.has_name());

    if (_converterCtx->getOutput(input.name()) == nullptr)
    {
      const auto &onnx_input_shape = input.type().tensor_type().shape();
      mir::Shape shape(onnx_input_shape.dim_size());
      for (int i = 0; i < onnx_input_shape.dim_size(); i++)
      {
        assert(onnx_input_shape.dim(i).has_dim_value());
        shape.dim(i) = static_cast<int32_t>(onnx_input_shape.dim(i).dim_value());
      }

      auto elem_type = onnxDataTypeToMirDataType(
        (onnx::TensorProto_DataType)input.type().tensor_type().elem_type());
      mir::TensorType type{elem_type, shape};
      auto *op = _graph->create<mir::ops::InputOp>(type);
      _converterCtx->setOutput(input.name(), op->getOutput(0));
    }
  }
}

std::unique_ptr<mir::Graph> ONNXImporterImpl::createIR()
{
  _graph = std::make_unique<mir::Graph>();
  _converterCtx = std::make_unique<ConverterContext>(_graph.get());

  createGraphInputs();

  // Forming partially ordered computation graph
  for (const auto &onnx_node : _model->graph().node())
  {
    assert(onnx_node.has_op_type());
    auto &op_type = onnx_node.op_type();
    auto opset = _modelCtx->getDomainOpsetVersion(onnx_node.domain());
    // Get converter
    NodeConverterRegistry::ConverterFunc converter =
      NodeConverterRegistry::getInstance().lookup(op_type, opset);
    assert(converter != nullptr);
    converter(onnx_node, _converterCtx.get());
  }
  // Set graph outputs
  const auto &outputs = _model->graph().output();
  for (const auto &output : outputs)
  {
    assert(output.has_name());
    auto mir_output = _converterCtx->getOutput(output.name());
    if (mir_output == nullptr)
      throw std::runtime_error("Bad output name!");

    _graph->create<mir::ops::OutputOp>(mir_output);
  }

  return std::move(_graph);
}

} // namespace

std::unique_ptr<mir::Graph> importModelFromBinaryFile(const std::string &filename)
{
  ONNXImporterImpl importer;
  return importer.importModelFromBinaryFile(filename);
}

std::unique_ptr<mir::Graph> importModelFromTextFile(const std::string &filename)
{
  ONNXImporterImpl importer;
  return importer.importModelFromTextFile(filename);
}

std::unique_ptr<mir::Graph> loadModel(const std::string &filename)
{
  return importModelFromBinaryFile(filename);
}

} // namespace mir_onnx