Caffe2 - Python API
A deep learning, cross platform ML framework
conversion.py
1 ## @package onnx
2 # Module caffe2.python.onnx.bin.conversion
3 
4 from __future__ import absolute_import
5 from __future__ import division
6 from __future__ import print_function
7 
8 import json
9 
10 from caffe2.proto import caffe2_pb2
11 import click
12 import numpy as np
13 from onnx import checker, ModelProto
14 
15 from caffe2.python.onnx.backend import Caffe2Backend as c2
16 import caffe2.python.onnx.frontend as c2_onnx
17 
18 
19 @click.command(
20  help='convert caffe2 net to onnx model',
21  context_settings={
22  'help_option_names': ['-h', '--help']
23  }
24 )
25 @click.argument('caffe2_net', type=click.File('rb'))
26 @click.option('--caffe2-net-name',
27  type=str,
28  help="Name of the caffe2 net")
29 @click.option('--caffe2-init-net',
30  type=click.File('rb'),
31  help="Path of the caffe2 init net pb file")
32 @click.option('--value-info',
33  type=str,
34  help='A json string providing the '
35  'type and shape information of the inputs')
36 @click.option('-o', '--output', required=True,
37  type=click.File('wb'),
38  help='Output path for the onnx model pb file')
39 def caffe2_to_onnx(caffe2_net,
40  caffe2_net_name,
41  caffe2_init_net,
42  value_info,
43  output):
44  c2_net_proto = caffe2_pb2.NetDef()
45  c2_net_proto.ParseFromString(caffe2_net.read())
46  if not c2_net_proto.name and not caffe2_net_name:
47  raise click.BadParameter(
48  'The input caffe2 net does not have name, '
49  '--caffe2-net-name must be provided')
50  c2_net_proto.name = caffe2_net_name or c2_net_proto.name
51  if caffe2_init_net:
52  c2_init_net_proto = caffe2_pb2.NetDef()
53  c2_init_net_proto.ParseFromString(caffe2_init_net.read())
54  c2_init_net_proto.name = '{}_init'.format(caffe2_net_name)
55  else:
56  c2_init_net_proto = None
57 
58  if value_info:
59  value_info = json.loads(value_info)
60 
61  onnx_model = c2_onnx.caffe2_net_to_onnx_model(
62  predict_net=c2_net_proto,
63  init_net=c2_init_net_proto,
64  value_info=value_info)
65 
66  output.write(onnx_model.SerializeToString())
67 
68 
69 @click.command(
70  help='convert onnx model to caffe2 net',
71  context_settings={
72  'help_option_names': ['-h', '--help']
73  }
74 )
75 @click.argument('onnx_model', type=click.File('rb'))
76 @click.option('-o', '--output', required=True,
77  type=click.File('wb'),
78  help='Output path for the caffe2 net file')
79 @click.option('--init-net-output',
80  required=True,
81  type=click.File('wb'),
82  help='Output path for the caffe2 init net file')
83 def onnx_to_caffe2(onnx_model, output, init_net_output):
84  onnx_model_proto = ModelProto()
85  onnx_model_proto.ParseFromString(onnx_model.read())
86 
87  init_net, predict_net = c2.onnx_graph_to_caffe2_net(onnx_model_proto)
88  init_net_output.write(init_net.SerializeToString())
89  output.write(predict_net.SerializeToString())