convert.py 9.3 KB
Newer Older
J
jiangjiajun 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#   Copyright (c) 2019  PaddlePaddle Authors. 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.
S
SunAhong1993 已提交
14

15 16
from six import text_type as _text_type
import argparse
J
jiangjiajun 已提交
17
import sys
18

J
jiangjiajun 已提交
19

20 21 22 23 24 25
def arg_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument("--model",
                        "-m",
                        type=_text_type,
                        default=None,
J
upgrade  
jiangjiajun 已提交
26
                        help="define model file path for tensorflow or onnx")
S
SunAhong1993 已提交
27
    parser.add_argument("--prototxt",
28 29 30
                        "-p",
                        type=_text_type,
                        default=None,
S
SunAhong1993 已提交
31
                        help="prototxt file of caffe model")
32 33 34 35 36 37 38 39 40 41
    parser.add_argument("--weight",
                        "-w",
                        type=_text_type,
                        default=None,
                        help="weight file of caffe model")
    parser.add_argument("--save_dir",
                        "-s",
                        type=_text_type,
                        default=None,
                        help="path to save translated model")
J
upgrade  
jiangjiajun 已提交
42 43 44 45 46 47
    parser.add_argument(
        "--framework",
        "-f",
        type=_text_type,
        default=None,
        help="define which deeplearning framework(tensorflow/caffe/onnx)")
S
SunAhong1993 已提交
48 49 50 51 52
    parser.add_argument(
        "--caffe_proto",
        "-c",
        type=_text_type,
        default=None,
J
upgrade  
jiangjiajun 已提交
53 54
        help="optional: the .py file compiled by caffe proto file of caffe model"
    )
J
jiangjiajun 已提交
55 56 57 58 59
    parser.add_argument("--version",
                        "-v",
                        action="store_true",
                        default=False,
                        help="get version of x2paddle")
60 61 62 63 64 65 66 67 68 69 70
    parser.add_argument(
        "--without_data_format_optimization",
        "-wo",
        action="store_true",
        default=False,
        help="tf model conversion without data format optimization")
    parser.add_argument("--define_input_shape",
                        "-d",
                        action="store_true",
                        default=False,
                        help="define input shape for tf model")
M
mamingjie-China 已提交
71
    parser.add_argument("--params_merge",
M
mamingjie-China 已提交
72 73 74 75
                        "-pm",
                        action="store_true",
                        default=False,
                        help="define whether merge the params")
J
jiangjiajun 已提交
76

77
    return parser
J
jiangjiajun 已提交
78

79

80 81 82
def tf2paddle(model_path,
              save_dir,
              without_data_format_optimization=False,
M
mamingjie-China 已提交
83
              define_input_shape=False,
M
mamingjie-China 已提交
84
              params_merge=False):
J
jiangjiajun 已提交
85 86
    # check tensorflow installation and version
    try:
87 88
        import os
        os.environ["TF_CPP_MIN_LOG_LEVEL"] = '3'
J
jiangjiajun 已提交
89 90 91 92
        import tensorflow as tf
        version = tf.__version__
        if version >= '2.0.0' or version < '1.0.0':
            print(
J
jiangjiajun@baidu.com 已提交
93
                "[ERROR] 1.0.0<=tensorflow<2.0.0 is required, and v1.14.0 is recommended"
J
jiangjiajun 已提交
94 95 96
            )
            return
    except:
J
jiangjiajun@baidu.com 已提交
97 98 99
        print(
            "[ERROR] Tensorflow is not installed, use \"pip install tensorflow\"."
        )
J
jiangjiajun 已提交
100 101
        return

J
jiangjiajun 已提交
102
    from x2paddle.decoder.tf_decoder import TFDecoder
J
jiangjiajun 已提交
103
    from x2paddle.op_mapper.tf_op_mapper import TFOpMapper
104
    from x2paddle.op_mapper.tf_op_mapper_nhwc import TFOpMapperNHWC
J
jiangjiajun 已提交
105
    from x2paddle.optimizer.tf_optimizer import TFOptimizer
J
jiangjiajun 已提交
106 107

    print("Now translating model from tensorflow to paddle.")
108 109 110 111 112 113 114
    model = TFDecoder(model_path, define_input_shape=define_input_shape)
    if not without_data_format_optimization:
        mapper = TFOpMapper(model)
        optimizer = TFOptimizer(mapper)
        # neccesary optimization
        optimizer.delete_redundance_code()
        # optimizer below is experimental
J
jiangjiajun 已提交
115
        optimizer.optimize_elementwise_op()
116 117
        optimizer.merge_activation()
        optimizer.merge_bias()
J
jiangjiajun 已提交
118 119 120 121 122
        optimizer.optimize_sub_graph()


#        optimizer.merge_batch_norm()
#        optimizer.merge_prelu()
123 124 125 126
    else:
        mapper = TFOpMapperNHWC(model)
        optimizer = TFOptimizer(mapper)
        optimizer.delete_redundance_code()
J
jiangjiajun 已提交
127
        optimizer.strip_graph()
128 129
        optimizer.merge_activation()
        optimizer.merge_bias()
J
jiangjiajun 已提交
130
        optimizer.make_nchw_input_output()
131
        optimizer.remove_transpose()
M
mamingjie-China 已提交
132
    mapper.save_inference_model(save_dir, params_merge)
133 134


M
mamingjie-China 已提交
135
def caffe2paddle(proto, weight, save_dir, caffe_proto, params_merge=False):
J
jiangjiajun 已提交
136 137
    from x2paddle.decoder.caffe_decoder import CaffeDecoder
    from x2paddle.op_mapper.caffe_op_mapper import CaffeOpMapper
138
    from x2paddle.optimizer.caffe_optimizer import CaffeOptimizer
S
SunAhong1993 已提交
139
    import google.protobuf as gpb
S
SunAhong1993 已提交
140 141 142 143 144
    ver_part = gpb.__version__.split('.')
    version_satisfy = False
    if (int(ver_part[0]) == 3 and int(ver_part[1]) >= 6) \
        or (int(ver_part[0]) > 3):
        version_satisfy = True
J
jiangjiajun@baidu.com 已提交
145
    assert version_satisfy, '[ERROR] google.protobuf >= 3.6.0 is required'
J
jiangjiajun 已提交
146
    print("Now translating model from caffe to paddle.")
S
SunAhong1993 已提交
147
    model = CaffeDecoder(proto, weight, caffe_proto)
J
jiangjiajun 已提交
148
    mapper = CaffeOpMapper(model)
149 150 151
    optimizer = CaffeOptimizer(mapper)
    optimizer.merge_bn_scale()
    optimizer.merge_op_activation()
M
mamingjie-China 已提交
152
    mapper.save_inference_model(save_dir, params_merge)
153 154


M
mamingjie-China 已提交
155
def onnx2paddle(model_path, save_dir, params_merge=False):
C
update  
channingss 已提交
156 157 158 159
    # check onnx installation and version
    try:
        import onnx
        version = onnx.version.version
160
        if version != '1.6.0':
J
jiangjiajun@baidu.com 已提交
161
            print("[ERROR] onnx==1.6.0 is required")
C
update  
channingss 已提交
162 163
            return
    except:
J
jiangjiajun@baidu.com 已提交
164
        print("[ERROR] onnx is not installed, use \"pip install onnx==1.6.0\".")
C
update  
channingss 已提交
165
        return
C
channingss 已提交
166
    print("Now translating model from onnx to paddle.")
C
update  
channingss 已提交
167

R
root 已提交
168
    from x2paddle.op_mapper.onnx_op_mapper import ONNXOpMapper
C
update  
channingss 已提交
169
    from x2paddle.decoder.onnx_decoder import ONNXDecoder
R
root 已提交
170
    from x2paddle.optimizer.onnx_optimizer import ONNXOptimizer
171
    import onnxruntime
R
root 已提交
172
    model = ONNXDecoder(model_path)
C
channingss 已提交
173
    mapper = ONNXOpMapper(model, save_dir)
C
update  
channingss 已提交
174
    optimizer = ONNXOptimizer(mapper)
C
channingss 已提交
175

C
update  
channingss 已提交
176
    optimizer.delete_redundance_code()
M
mamingjie-China 已提交
177
    mapper.save_inference_model(save_dir, params_merge)
C
update  
channingss 已提交
178 179


180
def main():
J
jiangjiajun 已提交
181
    if len(sys.argv) < 2:
C
update  
channingss 已提交
182
        print("Use \"x2paddle -h\" to print the help information")
J
jiangjiajun 已提交
183 184
        print("For more information, please follow our github repo below:)")
        print("\nGithub: https://github.com/PaddlePaddle/X2Paddle.git\n")
J
jiangjiajun 已提交
185 186
        return

187 188 189
    parser = arg_parser()
    args = parser.parse_args()

J
jiangjiajun 已提交
190
    if args.version:
J
jiangjiajun 已提交
191
        import x2paddle
M
mamingjie-China 已提交
192
        print("x2paddle-{} with python>=3.5, paddlepaddle>=1.6.0\n".format(
J
jiangjiajun 已提交
193
            x2paddle.__version__))
J
jiangjiajun 已提交
194 195
        return

J
Jason 已提交
196
    assert args.framework is not None, "--framework is not defined(support tensorflow/caffe/onnx)"
197
    assert args.save_dir is not None, "--save_dir is not defined"
M
mamingjie-China 已提交
198

R
root 已提交
199 200 201 202 203
    if args.framework == "onnx":
        try:
            import onnxruntime as rt
            version = rt.__version__
            if version != '1.0.0':
J
jiangjiajun@baidu.com 已提交
204
                print("[ERROR] onnxruntime==1.0.0 is required")
R
root 已提交
205 206
                return
        except:
M
mamingjie-China 已提交
207
            print(
J
jiangjiajun@baidu.com 已提交
208
                "[ERROR] onnxruntime is not installed, use \"pip install onnxruntime==1.0.0\"."
M
mamingjie-China 已提交
209 210
            )

M
mamingjie-China 已提交
211 212 213
    try:
        import paddle
        v0, v1, v2 = paddle.__version__.split('.')
J
jiangjiajun@baidu.com 已提交
214 215 216 217
        print("paddle.__version__ = {}".format(paddle.__version__))
        if v0 == '0' and v1 == '0' and v2 == '0':
            print("[WARNING] You are use develop version of paddlepaddle")
        elif int(v0) != 1 or int(v1) < 6:
J
jiangjiajun@baidu.com 已提交
218
            print("[ERROR] paddlepaddle>=1.6.0 is required")
M
mamingjie-China 已提交
219 220
            return
    except:
J
jiangjiajun@baidu.com 已提交
221 222 223
        print(
            "[ERROR] paddlepaddle not installed, use \"pip install paddlepaddle\""
        )
224 225

    if args.framework == "tensorflow":
J
jiangjiajun 已提交
226
        assert args.model is not None, "--model should be defined while translating tensorflow model"
227 228
        without_data_format_optimization = False
        define_input_shape = False
M
mamingjie-China 已提交
229
        params_merge = False
230 231 232 233
        if args.without_data_format_optimization:
            without_data_format_optimization = True
        if args.define_input_shape:
            define_input_shape = True
M
mamingjie-China 已提交
234 235
        if args.params_merge:
            params_merge = True
236
        tf2paddle(args.model, args.save_dir, without_data_format_optimization,
M
mamingjie-China 已提交
237
                  define_input_shape, params_merge)
238 239

    elif args.framework == "caffe":
S
SunAhong1993 已提交
240
        assert args.prototxt is not None and args.weight is not None, "--prototxt and --weight should be defined while translating caffe model"
M
mamingjie-China 已提交
241 242 243
        params_merge = False
        if args.params_merge:
            params_merge = True
S
SunAhong1993 已提交
244
        caffe2paddle(args.prototxt, args.weight, args.save_dir,
M
mamingjie-China 已提交
245
                     args.caffe_proto, params_merge)
C
update  
channingss 已提交
246 247
    elif args.framework == "onnx":
        assert args.model is not None, "--model should be defined while translating onnx model"
M
mamingjie-China 已提交
248 249 250 251
        params_merge = False
        if args.params_merge:
            params_merge = True
        onnx2paddle(args.model, args.save_dir, params_merge)
252
    else:
C
update  
channingss 已提交
253
        raise Exception("--framework only support tensorflow/caffe/onnx now")
254 255 256 257


if __name__ == "__main__":
    main()