convert.py 12.0 KB
Newer Older
1
# Copyright (c) 2020  PaddlePaddle Authors. All Rights Reserved.
J
jiangjiajun 已提交
2 3 4 5 6 7 8 9 10 11 12 13
#
# 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
from six import text_type as _text_type
S
SunAhong1993 已提交
16
from x2paddle import program
17
import argparse
J
jiangjiajun 已提交
18
import sys
19

J
jiangjiajun 已提交
20

21 22
def arg_parser():
    parser = argparse.ArgumentParser()
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
    parser.add_argument(
        "--model",
        "-m",
        type=_text_type,
        default=None,
        help="define model file path for tensorflow or onnx")
    parser.add_argument(
        "--prototxt",
        "-p",
        type=_text_type,
        default=None,
        help="prototxt file of caffe model")
    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 已提交
47 48 49 50 51
    parser.add_argument(
        "--framework",
        "-f",
        type=_text_type,
        default=None,
52 53
        help="define which deeplearning framework(tensorflow/caffe/onnx/paddle2onnx)"
    )
S
SunAhong1993 已提交
54 55 56 57 58
    parser.add_argument(
        "--caffe_proto",
        "-c",
        type=_text_type,
        default=None,
J
upgrade  
jiangjiajun 已提交
59 60
        help="optional: the .py file compiled by caffe proto file of caffe model"
    )
61 62 63 64 65 66
    parser.add_argument(
        "--version",
        "-v",
        action="store_true",
        default=False,
        help="get version of x2paddle")
67 68 69
    parser.add_argument(
        "--without_data_format_optimization",
        "-wo",
S
SunAhong1993 已提交
70 71
        type=_text_type,
        default="True",
72
        help="tf model conversion without data format optimization")
73 74 75 76 77 78
    parser.add_argument(
        "--define_input_shape",
        "-d",
        action="store_true",
        default=False,
        help="define input shape for tf model")
C
Channingss 已提交
79 80 81 82 83 84
    parser.add_argument(
        "--onnx_opset",
        "-oo",
        type=int,
        default=10,
        help="when paddle2onnx set onnx opset version to export")
85 86 87 88 89 90
    parser.add_argument(
        "--params_merge",
        "-pm",
        action="store_true",
        default=False,
        help="define whether merge the params")
S
SunAhong1993 已提交
91 92 93 94 95 96 97 98
    parser.add_argument(
        "--paddle_type",
        "-pt",
        type=_text_type,
        default="dygraph",
        help="define the paddle model type after converting(dygraph/static)"
    )
    
99
    return parser
J
jiangjiajun 已提交
100

C
Channingss 已提交
101

102 103
def tf2paddle(model_path,
              save_dir,
J
jiangjiajun 已提交
104
              without_data_format_optimization=False,
M
mamingjie-China 已提交
105
              define_input_shape=False,
S
SunAhong1993 已提交
106
              paddle_type="dygraph",
M
mamingjie-China 已提交
107
              params_merge=False):
J
jiangjiajun 已提交
108 109
    # check tensorflow installation and version
    try:
110 111
        import os
        os.environ["TF_CPP_MIN_LOG_LEVEL"] = '3'
J
jiangjiajun 已提交
112 113 114 115
        import tensorflow as tf
        version = tf.__version__
        if version >= '2.0.0' or version < '1.0.0':
            print(
J
jiangjiajun@baidu.com 已提交
116
                "[ERROR] 1.0.0<=tensorflow<2.0.0 is required, and v1.14.0 is recommended"
J
jiangjiajun 已提交
117 118 119
            )
            return
    except:
J
jiangjiajun@baidu.com 已提交
120 121 122
        print(
            "[ERROR] Tensorflow is not installed, use \"pip install tensorflow\"."
        )
J
jiangjiajun 已提交
123
        return
S
SunAhong1993 已提交
124
    
J
jiangjiajun 已提交
125
    from x2paddle.decoder.tf_decoder import TFDecoder
S
SunAhong1993 已提交
126 127 128 129 130
    if paddle_type == "dygraph":
        from x2paddle.op_mapper.dygraph.tf2paddle.tf_op_mapper import TFOpMapper
    else:
        from x2paddle.op_mapper.static.tf2paddle.tf_op_mapper import TFOpMapper
        
S
SunAhong1993 已提交
131
    
J
jiangjiajun 已提交
132
    print("Now translating model from tensorflow to paddle.")
133
    model = TFDecoder(model_path, define_input_shape=define_input_shape)
S
SunAhong1993 已提交
134
    mapper = TFOpMapper(model)
S
SunAhong1993 已提交
135
    mapper.paddle_graph.build()
S
SunAhong1993 已提交
136 137 138 139 140 141 142 143
    if paddle_type == "dygraph":
        from x2paddle.optimizer.optimizer import GraphOptimizer
        graph_opt = GraphOptimizer(source_frame="tf", paddle_type=paddle_type)
        graph_opt.optimize(mapper.paddle_graph)
    else:
        from x2paddle.optimizer.tensorflow.bias import BiasOpt
        from x2paddle.optimizer.tensorflow.transpose import TransposeOpt
        from x2paddle.optimizer.tensorflow.batch_norm import BatchNormOpt
S
SunAhong1993 已提交
144
        from x2paddle.optimizer.tensorflow.prelu import PReLUOpt
S
SunAhong1993 已提交
145 146 147
        bias_opt = BiasOpt()
        transpose_opt = TransposeOpt()
        batch_norm_opt = BatchNormOpt()
S
SunAhong1993 已提交
148
        prelu_opt = PReLUOpt()
S
SunAhong1993 已提交
149 150
        bias_opt.run(mapper.paddle_graph)
        batch_norm_opt.run(mapper.paddle_graph)
S
SunAhong1993 已提交
151
        prelu_opt.run(mapper.paddle_graph)
S
SunAhong1993 已提交
152
        transpose_opt.run(mapper.paddle_graph)
S
SunAhong1993 已提交
153 154
    mapper.paddle_graph.gen_model(save_dir)
        
155 156


S
SunAhong1993 已提交
157 158
def caffe2paddle(proto, weight, save_dir, caffe_proto, 
                 paddle_type, params_merge=False):
S
SunAhong1993 已提交
159
    from x2paddle.decoder.caffe_decoder import CaffeDecoder
S
SunAhong1993 已提交
160
    if paddle_type == "dygraph":
S
SunAhong1993 已提交
161
        from x2paddle.op_mapper.dygraph.caffe2paddle.caffe_op_mapper import CaffeOpMapper
S
SunAhong1993 已提交
162
    else:
S
SunAhong1993 已提交
163
        from x2paddle.op_mapper.static.caffe2paddle.caffe_op_mapper import CaffeOpMapper
S
SunAhong1993 已提交
164
    import google.protobuf as gpb
S
SunAhong1993 已提交
165 166 167 168 169
    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 已提交
170
    assert version_satisfy, '[ERROR] google.protobuf >= 3.6.0 is required'
J
jiangjiajun 已提交
171
    print("Now translating model from caffe to paddle.")
S
SunAhong1993 已提交
172 173 174 175 176 177 178 179 180
    model = CaffeDecoder(proto, weight, caffe_proto)
    mapper = CaffeOpMapper(model)
    mapper.paddle_graph.build()
    print("Model optimizing ...")
    from x2paddle.optimizer.optimizer import GraphOptimizer
    graph_opt = GraphOptimizer(source_frame="caffe", paddle_type=paddle_type)
    graph_opt.optimize(mapper.paddle_graph)
    print("Model optimized.")
    mapper.paddle_graph.gen_model(save_dir)
181 182


S
SunAhong1993 已提交
183
def onnx2paddle(model_path, save_dir, paddle_type, params_merge=False):
C
update  
channingss 已提交
184 185 186 187
    # check onnx installation and version
    try:
        import onnx
        version = onnx.version.version
S
SunAhong1993 已提交
188 189
        if version < '1.6.0':
            print("[ERROR] onnx>=1.6.0 is required")
C
update  
channingss 已提交
190 191
            return
    except:
J
jiangjiajun@baidu.com 已提交
192
        print("[ERROR] onnx is not installed, use \"pip install onnx==1.6.0\".")
C
update  
channingss 已提交
193
        return
C
channingss 已提交
194
    print("Now translating model from onnx to paddle.")
C
update  
channingss 已提交
195 196

    from x2paddle.decoder.onnx_decoder import ONNXDecoder
S
SunAhong1993 已提交
197 198 199 200
    if paddle_type == "dygraph":
        from x2paddle.op_mapper.dygraph.onnx2paddle.onnx_op_mapper import ONNXOpMapper
    else:
        from x2paddle.op_mapper.static.onnx2paddle.onnx_op_mapper import ONNXOpMapper
R
root 已提交
201
    model = ONNXDecoder(model_path)
C
Channingss 已提交
202
    mapper = ONNXOpMapper(model)
S
SunAhong1993 已提交
203 204 205 206 207 208 209 210 211 212
    if paddle_type == "dygraph":
        mapper.paddle_graph.build()
        mapper.paddle_graph.gen_model(save_dir)
    else:
        from x2paddle.optimizer.onnx_optimizer import ONNXOptimizer
        print("Model optimizing ...")
        optimizer = ONNXOptimizer(mapper)
        optimizer.delete_redundance_code()
        print("Model optimized.")
        mapper.save_inference_model(save_dir, params_merge)
C
Channingss 已提交
213 214


S
SunAhong1993 已提交
215
def pytorch2paddle(module, save_dir, jit_type="trace", input_examples=None):
S
SunAhong1993 已提交
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
    # check pytorch installation and version
    try:
        import torch
        version = torch.__version__
        ver_part = version.split('.')
        print(ver_part)
        if int(ver_part[1]) < 5:
            print("[ERROR] pytorch>=1.5.0 is required")
            return
    except:
        print(
            "[ERROR] Pytorch is not installed, use \"pip install torch==1.5.0 torchvision\"."
        )
        return
    print("Now translating model from pytorch to paddle.")
S
SunAhong1993 已提交
231
    
S
SunAhong1993 已提交
232
    from x2paddle.decoder.pytorch_decoder import ScriptDecoder, TraceDecoder
S
SunAhong1993 已提交
233 234
    from x2paddle.op_mapper.dygraph.pytorch2paddle.pytorch_op_mapper import PyTorchOpMapper

S
SunAhong1993 已提交
235
    if jit_type == "trace":
S
SunAhong1993 已提交
236
        model = TraceDecoder(module, input_examples)
S
SunAhong1993 已提交
237
    else:
S
SunAhong1993 已提交
238
        model = ScriptDecoder(module, input_examples)
S
SunAhong1993 已提交
239 240
    mapper = PyTorchOpMapper(model)
    mapper.paddle_graph.build()
S
SunAhong1993 已提交
241
    print("Model optimizing ...")
S
SunAhong1993 已提交
242 243 244
    from x2paddle.optimizer.optimizer import GraphOptimizer
    graph_opt = GraphOptimizer(source_frame="pytorch", paddle_type="dygraph", jit_type=jit_type)
    graph_opt.optimize(mapper.paddle_graph)
S
SunAhong1993 已提交
245
    print("Model optimized.")
S
SunAhong1993 已提交
246
    mapper.paddle_graph.gen_model(save_dir, jit_type=jit_type)
S
SunAhong1993 已提交
247 248


J
Jason 已提交
249
def paddle2onnx(model_path, save_dir, opset_version=10):
S
SunAhong1993 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
    import paddle.fluid as fluid
    try:
        import paddle2onnx
    except:
        print(
            "[ERROR] paddle2onnx not installed, use \"pip install paddle2onnx\"")

    import paddle2onnx as p2o
    model = p2o.PaddleDecoder(model_path, '__model__', '__params__')
    mapper = p2o.PaddleOpMapper()
    mapper.convert(
        model.program,
        save_dir,
        scope=fluid.global_scope(),
        opset_version=opset_version)
C
update  
channingss 已提交
265 266


267
def main():
J
jiangjiajun 已提交
268
    if len(sys.argv) < 2:
C
update  
channingss 已提交
269
        print("Use \"x2paddle -h\" to print the help information")
J
jiangjiajun 已提交
270 271
        print("For more information, please follow our github repo below:)")
        print("\nGithub: https://github.com/PaddlePaddle/X2Paddle.git\n")
J
jiangjiajun 已提交
272 273
        return

274 275 276
    parser = arg_parser()
    args = parser.parse_args()

J
jiangjiajun 已提交
277
    if args.version:
J
jiangjiajun 已提交
278
        import x2paddle
M
mamingjie-China 已提交
279
        print("x2paddle-{} with python>=3.5, paddlepaddle>=1.6.0\n".format(
J
jiangjiajun 已提交
280
            x2paddle.__version__))
J
jiangjiajun 已提交
281 282
        return

J
Jason 已提交
283
    assert args.framework is not None, "--framework is not defined(support tensorflow/caffe/onnx)"
284
    assert args.save_dir is not None, "--save_dir is not defined"
S
SunAhong1993 已提交
285
    assert args.paddle_type in ["dygraph", "static"], "--paddle_type must be 'dygraph' or 'static'"
M
mamingjie-China 已提交
286

M
mamingjie-China 已提交
287 288 289
    try:
        import paddle
        v0, v1, v2 = paddle.__version__.split('.')
290 291 292
        print("paddle.__version__ = {}".format(paddle.__version__))
        if v0 == '0' and v1 == '0' and v2 == '0':
            print("[WARNING] You are use develop version of paddlepaddle")
S
SunAhong1993 已提交
293 294
        elif int(v0) != 2 or int(v1) < 0:
            print("[ERROR] paddlepaddle>=2.0.0 is required")
M
mamingjie-China 已提交
295 296
            return
    except:
J
jiangjiajun@baidu.com 已提交
297 298 299
        print(
            "[ERROR] paddlepaddle not installed, use \"pip install paddlepaddle\""
        )
300 301

    if args.framework == "tensorflow":
J
jiangjiajun 已提交
302
        assert args.model is not None, "--model should be defined while translating tensorflow model"
S
SunAhong1993 已提交
303 304 305
        assert args.without_data_format_optimization in [
            "True", "False"
        ], "--the param without_data_format_optimization should be defined True or False"
306
        define_input_shape = False
M
mamingjie-China 已提交
307
        params_merge = False
S
SunAhong1993 已提交
308
        without_data_format_optimization = True if args.without_data_format_optimization == "True" else False
309 310
        if args.define_input_shape:
            define_input_shape = True
M
mamingjie-China 已提交
311 312
        if args.params_merge:
            params_merge = True
313
        tf2paddle(args.model, args.save_dir, without_data_format_optimization,
S
SunAhong1993 已提交
314
                  define_input_shape, args.paddle_type, params_merge)
315 316

    elif args.framework == "caffe":
S
SunAhong1993 已提交
317
        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 已提交
318 319 320
        params_merge = False
        if args.params_merge:
            params_merge = True
S
SunAhong1993 已提交
321
        caffe2paddle(args.prototxt, args.weight, args.save_dir,
S
SunAhong1993 已提交
322
                     args.caffe_proto, args.paddle_type, params_merge)
C
update  
channingss 已提交
323 324
    elif args.framework == "onnx":
        assert args.model is not None, "--model should be defined while translating onnx model"
M
mamingjie-China 已提交
325
        params_merge = False
326

M
mamingjie-China 已提交
327 328
        if args.params_merge:
            params_merge = True
S
SunAhong1993 已提交
329
        onnx2paddle(args.model, args.save_dir, args.paddle_type, params_merge)
330 331
    elif args.framework == "paddle2onnx":
        assert args.model is not None, "--model should be defined while translating paddle model to onnx"
S
SunAhong1993 已提交
332
        paddle2onnx(args.model, args.save_dir, opset_version=args.onnx_opset)
333

334
    else:
335 336
        raise Exception(
            "--framework only support tensorflow/caffe/onnx/paddle2onnx now")
337 338 339


if __name__ == "__main__":
C
Channingss 已提交
340
    main()