harry
harry

Reputation: 1093

setup onnx to parsing onnx graph in c++

I'm trying to load an onnx file and print all the tensor dimensions in the graph(has to perform shape inference). I can do this in python by just importing from onnx import shape_inference, onnx. Is there any documentation on setting up onnx to use it in a c++ program?

Upvotes: 1

Views: 1025

Answers (2)

Changming Sun
Changming Sun

Reputation: 935

Read protobuf's C++ tutorial first: https://protobuf.dev/getting-started/cpptutorial/. Then In ONNX's source code you can find a few *.proto(or *.proto3) files. You can use protobuf's protoc tool to generate C++ stubs from the *.proto files. Then you can load your model in a way like:

int main(int argc, char* argv[]) {
  // Verify that the version of the library that we linked against is
  // compatible with the version of the headers we compiled against.
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  if (argc != 2) {
    cerr << "Usage:  " << argv[0] << " MODEL_FILE" << endl;
    return -1;
  }

  onnx::ModelProto model_proto;

  {
    fstream input(argv[1], ios::in | ios::binary);
    if (!input) {
      cout << argv[1] << ": File not found.  Creating a new file." << endl;
    } else if (!model_proto.ParseFromIstream(&input)) {
      cerr << "Failed to parse the ONNX model." << endl;
      return -1;
    }
  }
  //TODO: Then get the graph from the model_proto and iterate all its nodes

  return 0;

Upvotes: 0

harry
harry

Reputation: 1093

If anyone looking for a solution, I've created a project here which uses libonnx.so to perform shape inference.

Upvotes: 2

Related Questions