program.py 27.6 KB
Newer Older
S
SunAhong1993 已提交
1
# -*- coding:UTF-8 -*-
S
SunAhong1993 已提交
2
#   Copyright (c) 2020  PaddlePaddle Authors. All Rights Reserved.
J
jiangjiajun 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#
# 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.

from __future__ import print_function
from __future__ import division
S
SunAhong1993 已提交
18 19 20
import paddle.fluid as fluid
import paddle
from paddle.fluid.proto import framework_pb2
C
Channingss 已提交
21
import collections
S
SunAhong1993 已提交
22 23
import numpy
import sys
J
jiangjiajun 已提交
24
import os
S
SunAhong1993 已提交
25 26
import six
import pickle
S
SunAhong1993 已提交
27
import numpy as np
S
SunAhong1993 已提交
28
from os import path as osp 
S
SunAhong1993 已提交
29
from x2paddle.core.util import *
J
jiangjiajun 已提交
30 31 32


class PaddleLayer(object):
S
SunAhong1993 已提交
33
    def __init__(self, id, kernel, inputs, outputs, scope_name="", **kwargs):
J
jiangjiajun 已提交
34 35 36 37 38
        assert isinstance(
            inputs,
            dict), "parameter 'inputs' for PaddleLayer should be type of dict"
        assert isinstance(
            outputs,
S
SunAhong1993 已提交
39 40
            list), "parameter 'outputs' for PaddleLayer should be type of list"
        for k, v in inputs.items():
C
Channingss 已提交
41
            if isinstance(v, (list, tuple)):
S
SunAhong1993 已提交
42 43 44 45 46 47 48 49 50 51 52 53
                for i in v:
                    assert isinstance(
                        i, six.string_types
                    ), "value in inputs should be type of string or list of string"
            else:
                assert isinstance(v, six.string_types) or isinstance(
                    v, list
                ), "value in inputs should be type of string or list of string"
        for v in outputs:
            assert isinstance(
                v, six.
                string_types), "elements in outputs should be type of string"
J
jiangjiajun 已提交
54 55 56
        self.kernel = kernel
        self.inputs = inputs
        self.outputs = outputs
S
SunAhong1993 已提交
57
        self.scope_name = scope_name
J
jiangjiajun 已提交
58
        self.attrs = kwargs
S
SunAhong1993 已提交
59 60
        self.id = id
        self.blocks = list()
S
SunAhong1993 已提交
61
        
S
SunAhong1993 已提交
62 63 64

    def add_block(self, block):
        self.blocks.append(block)
J
jiangjiajun 已提交
65 66


S
SunAhong1993 已提交
67
class PaddleGraph(object):
S
SunAhong1993 已提交
68
    def __init__(self, source_type=None, parent_layer=None, graph_type="static"):
C
Channingss 已提交
69
        self.layers = collections.OrderedDict()
J
jiangjiajun 已提交
70 71 72 73 74
        self.edges_out = dict()
        self.edges_in = dict()
        self.inputs = list()
        self.outputs = list()
        self.parameters = dict()
S
SunAhong1993 已提交
75 76
        self.parent_layer = parent_layer
        self.graph_type = graph_type
S
SunAhong1993 已提交
77 78
        self.source_type = source_type
        self.custom_code = None
S
SunAhong1993 已提交
79
        self.inputs_info = None
S
SunAhong1993 已提交
80

S
SunAhong1993 已提交
81
    def set_name(self, name):
S
SunAhong1993 已提交
82
        self.name = name.replace("-", "_").replace("/", "_")
S
SunAhong1993 已提交
83 84 85

    def set_parameters(self, parameters):
        self.parameters = parameters
S
SunAhong1993 已提交
86
        
S
SunAhong1993 已提交
87 88
    def set_custom(self, custom_code):
        self.custom_code = custom_code
S
SunAhong1993 已提交
89 90 91 92 93 94
        
    def set_inputs_info(self, inputs_info):
        self.inputs_info = inputs_info
        
    def set_script(self, script):
        self.script = script
S
SunAhong1993 已提交
95 96

    def clear(self):
C
Channingss 已提交
97
        self.layers = collections.OrderedDict()
S
SunAhong1993 已提交
98 99 100 101 102 103 104 105 106
        self.edges_out = dict()
        self.edges_in = dict()
        self.inputs = list()
        self.outputs = list()
        self.parameters = dict()

    def clear_edges(self):
        self.edges_out = dict()
        self.edges_in = dict()
J
jiangjiajun 已提交
107

S
SunAhong1993 已提交
108
    def add_layer(self, kernel, inputs, outputs, scope_name="", **kwargs):
S
SunAhong1993 已提交
109 110 111 112 113
        layer_id = str(len(self.layers))
        if self.parent_layer is not None:
            layer_id = "{}.{}.{}".format(self.parent_layer.id,
                                         len(self.parent_layer.blocks),
                                         layer_id)
S
SunAhong1993 已提交
114
        layer = PaddleLayer(layer_id, kernel, inputs, outputs, scope_name=scope_name, **kwargs)
S
SunAhong1993 已提交
115 116
        self.layers[layer_id] = layer
        return layer_id
J
jiangjiajun 已提交
117

J
jiangjiajun 已提交
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
    def del_layer(self, layer_id):
        layer = self.layers[layer_id]
        outputs = self.edges_out.get(layer_id, [])
        inputs = self.edges_in.get(layer_id, [])

        assert len(
            inputs) <= 1, "There should be 0 or 1 input for deleted layer."

        if len(inputs) == 0:
            for out in outputs:
                while layer_id in self.edges_in[out]:
                    index = self.edges_in[out].index(layer_id)
                    del self.edges_in[out][index]

                input_keys = list(self.layers[out].inputs.keys())
                for k in input_keys:
                    if self.layers[out].inputs[k] == layer.outputs[0]:
                        del self.layers[out].inputs[k]

            del self.layers[layer_id]
            if layer_id in self.edges_in:
                del self.edges_in[layer_id]
            if layer_id in self.edges_out:
                del self.edges_out[layer_id]
            return

        # 将所有输出layer的输入layer进行替换
        for out in outputs:
            for i in range(len(self.edges_in[out])):
                if self.edges_in[out][i] == layer_id:
                    self.edges_in[out][i] = inputs[0]

        # 将输出layer赋给输入layer的输出
        replace_index = self.edges_out[inputs[0]].index(layer_id)
        del self.edges_out[inputs[0]][replace_index]
        for i, out in enumerate(outputs):
            self.edges_out[inputs[0]].insert(replace_index + i, out)
            for k, v in self.layers[out].inputs.items():
                if v == layer.outputs[0]:
                    self.layers[out].inputs[k] = list(layer.inputs.values())[0]

        del self.layers[layer_id]
        if layer_id in self.edges_out:
            del self.edges_out[layer_id]
        if layer_id in self.edges_in:
            del self.edges_in[layer_id]

S
SunAhong1993 已提交
165 166 167 168
    def build(self, inputs=None, outputs=None):
        self.clear_edges()
        outputs_from_nodes = dict()
        for layer_id, layer in self.layers.items():
C
Channingss 已提交
169
            print(layer.kernel, layer.outputs ,layer.inputs)
S
SunAhong1993 已提交
170 171
            for input_key, input_var in layer.inputs.items():
                vs = input_var
C
Channingss 已提交
172
                if not isinstance(vs, (list, tuple)):
S
SunAhong1993 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
                    vs = [vs]
                for v in vs:
                    assert v in outputs_from_nodes or (
                        inputs is not None and v in list(inputs.values())
                    ) or (
                        outputs is not None and v in outputs
                    ), "Couldn't find {} in previous layers, the layers should be make by topological sort".format(
                        v)
                    if v in outputs_from_nodes:
                        in_layer_id = outputs_from_nodes[v]
                    else:
                        in_layer_id = -1
                    if in_layer_id not in self.edges_out:
                        self.edges_out[in_layer_id] = list()
                    self.edges_out[in_layer_id].append(layer_id)

                    if layer_id not in self.edges_in:
                        self.edges_in[layer_id] = list()
                    self.edges_in[layer_id].append(in_layer_id)
J
jiangjiajun 已提交
192
            for output in layer.outputs:
S
SunAhong1993 已提交
193
                outputs_from_nodes[output] = layer_id
J
jiangjiajun 已提交
194

S
SunAhong1993 已提交
195 196 197 198 199 200
            # 将block的输出用于父图
            if inputs is not None and outputs is not None and set(
                    layer.outputs).issubset(outputs):
                if layer_id not in self.edges_out:
                    self.edges_out[layer_id] = list()
                self.edges_out[layer_id].append(-1)
J
jiangjiajun 已提交
201

S
SunAhong1993 已提交
202 203 204 205
            # 处理子图
            if len(layer.blocks) > 0:
                for block in layer.blocks:
                    block.build(layer.inputs, layer.outputs)
J
jiangjiajun 已提交
206

S
SunAhong1993 已提交
207 208 209 210 211 212 213 214
        # 删除不必要的节点
        invalid_list = list()
        for layer_id, layer in self.layers.items():
            if len(self.layers) > 1:
                if self.edges_in.get(layer_id, 0) == 0 and self.edges_out.get(
                        layer_id, 0) == 0 and layer.kernel != "prim.assert" \
                        and layer.kernel != "prim.exception" \
                        and layer.kernel != "prim.warnings":
S
SunAhong1993 已提交
215 216
                    if layer.kernel == "paddle.to_tensor":
                        self.inputs_info.pop(layer.outputs[0])
S
SunAhong1993 已提交
217 218 219
                    invalid_list.append(layer_id)
        for layer_id in invalid_list:
            self.layers.pop(layer_id)
J
jiangjiajun 已提交
220

S
SunAhong1993 已提交
221 222 223 224
        if self.graph_type == "dygraph":
            self.get_dygraph_inputs()
            if len(self.outputs) == 0:
                self.get_dygraph_outputs()
J
jiangjiajun 已提交
225

S
SunAhong1993 已提交
226 227 228 229 230 231 232 233 234 235 236
    def get_global_layers(self):
        # 该全局layers的信息是按照拓扑排序组成的
        def update(layers):
            global_layers = dict()
            for layer_id, layer in layers.items():
                global_layers[layer_id] = layer
                for block in layer.blocks:
                    block_global_layers = update(block.layers)
                    global_layers.update(block_global_layers)
            return global_layers
        return update(self.layers)
S
SunAhong1993 已提交
237 238
    
    def gen_model(self, save_dir, jit_type=None):
S
SunAhong1993 已提交
239
        if not osp.exists(save_dir):
S
SunAhong1993 已提交
240 241
            os.makedirs(save_dir)
        if self.graph_type == "static":
S
SunAhong1993 已提交
242
            self.gen_static_model(save_dir)
S
SunAhong1993 已提交
243
        else:
S
SunAhong1993 已提交
244 245 246
            self.gen_dygraph_model(save_dir, jit_type)
                
    def gen_static_model(self, save_dir):
S
SunAhong1993 已提交
247 248
        code_dir = osp.join(save_dir, 'model_with_code')
        infer_dir = osp.join(save_dir, 'inference_model')
S
SunAhong1993 已提交
249 250 251 252 253 254 255 256 257 258 259 260
        self.gen_static_code(code_dir)
        sys.path.append(code_dir)
        import x2paddle_model
        paddle.enable_static()
        scope = paddle.static.Scope()
        startup_program = paddle.static.Program()
        main_program = paddle.static.Program()
        with paddle.static.scope_guard(scope):
            with paddle.static.program_guard(main_program, startup_program):
                inputs, outputs = x2paddle_model.x2paddle_net()
                exe = fluid.Executor(fluid.CPUPlace())
                exe.run(startup_program)
S
SunAhong1993 已提交
261
                param_dir = osp.join(code_dir, 'weights')
S
SunAhong1993 已提交
262 263 264 265
                for k, v in self.parameters.items():
                    if scope.find_var(k):
                        self.dump_parameter(k, v, param_dir)
                def if_exist(var):
S
SunAhong1993 已提交
266 267
                    b = osp.exists(
                        osp.join(osp.join(param_dir, var.name)))
S
SunAhong1993 已提交
268 269 270 271 272 273 274 275 276 277 278
                    return b
                fluid.io.load_vars(
                    exe, param_dir, main_program, predicate=if_exist)
                fluid.io.save_inference_model(
                    dirname=infer_dir,
                    feeded_var_names=[i.name for i in inputs],
                    target_vars=outputs,
                    executor=exe)
                
    def gen_dygraph_model(self, save_dir, jit_type=None):
        if jit_type == "trace":
S
SunAhong1993 已提交
279
            from x2paddle.optimizer.pytorch_code_optimizer import HierarchicalTree
S
SunAhong1993 已提交
280 281 282 283 284 285
            hierarchical_tree = HierarchicalTree(self)
            for layer_id, layer in self.layers.items():
                hierarchical_tree.insert(layer)
            hierarchical_tree.save_source_files(save_dir)
            self.dump_dygraph_parameter(save_dir)
        else:
S
SunAhong1993 已提交
286
            if self.source_type == "pytorch":
S
SunAhong1993 已提交
287
                from x2paddle.optimizer.pytorch_code_optimizer import ModuleGraph
S
SunAhong1993 已提交
288 289 290 291 292 293
                module_graph = ModuleGraph(self)
                module_graph.save_source_files(save_dir)
                self.dump_dygraph_parameter(save_dir)
            else:
                self.gen_dygraph_code(save_dir)
                self.dump_dygraph_parameter(save_dir)
S
SunAhong1993 已提交
294
        # 动转静
S
SunAhong1993 已提交
295 296
        code_path = osp.join(osp.abspath(save_dir), "x2paddle_code.py")
        print("Exporting inference model from python code ('{}')... \n".format(code_path))
S
SunAhong1993 已提交
297
        if len(self.inputs_info) > 0:
S
SunAhong1993 已提交
298 299 300 301 302
            input_shapes = list()
            input_types = list()
            for input_name in self.inputs:
                input_shapes.append(self.inputs_info[input_name][0])
                input_types.append(self.inputs_info[input_name][1])
S
SunAhong1993 已提交
303 304
            try:
                self.dygraph2static(save_dir, input_shapes, input_types)
S
SunAhong1993 已提交
305
            except Exception as e:
S
SunAhong1993 已提交
306
                print("Fail to generate inference model! Problem happend while export inference model from python code '{}';\n".format(code_path))
S
SunAhong1993 已提交
307 308
                print("===================Error Information===============")
                raise e
S
SunAhong1993 已提交
309 310

    def gen_static_code(self, code_dir):
J
jiangjiajun 已提交
311 312 313 314 315 316 317 318
        def write_code(f, code_list, indent=0):
            indent_blank = "    " * indent
            for code_line in code_list:
                if code_line.strip() == "":
                    f.write('\n')
                else:
                    f.write(indent_blank + code_line + '\n')

S
SunAhong1993 已提交
319
        if not osp.exists(code_dir):
S
SunAhong1993 已提交
320
            os.makedirs(code_dir)
S
SunAhong1993 已提交
321
        f = open(osp.join(code_dir, 'x2paddle_model.py'), 'w')
S
SunAhong1993 已提交
322 323 324 325 326 327
        
        if self.source_type == "caffe":
            custom_import = "from x2paddle.op_mapper.static.caffe2paddle " + \
                             "import caffe_custom_layer as x2paddle_nn"
        else:
            custom_import = ""
J
jiangjiajun 已提交
328 329 330

        write_code(
            f, [
S
SunAhong1993 已提交
331
                custom_import,
S
SunAhong1993 已提交
332 333 334
                "import paddle", 
                "import math", 
                "",
J
jiangjiajun 已提交
335 336
            ],
            indent=0)
S
SunAhong1993 已提交
337
        if self.custom_code is not None:
S
SunAhong1993 已提交
338 339
            write_code(
                f, 
S
SunAhong1993 已提交
340
                list(self.custom_code.values()),
S
SunAhong1993 已提交
341 342 343 344 345 346 347 348 349
                indent=0)
        write_code(f, 
            ["", "def x2paddle_net():"],
            indent=0)
        write_code(
            f, [
                "paddle.enable_static()"
            ],
            indent=1)
S
SunAhong1993 已提交
350
        for layer_id, layer in self.layers.items():
S
SunAhong1993 已提交
351 352
            if layer.kernel.startswith("paddle"):
                remove_default_attrs(layer.kernel, layer.attrs)
S
SunAhong1993 已提交
353 354 355
            edges_in = self.edges_in.get(layer_id, [])
            edges_out = self.edges_out.get(layer_id, [])
            if len(edges_in) == 0 and len(edges_out) == 0:
J
jiangjiajun 已提交
356 357 358 359 360 361 362 363 364 365
                continue

            line = ""

            if len(layer.outputs) == 1:
                line = layer.outputs[0]
            else:
                for output in layer.outputs:
                    line += "{}, ".format(output)
                line = line.strip(", ")
S
SunAhong1993 已提交
366
            if layer.kernel.startswith("custom_layer"):
S
SunAhong1993 已提交
367
                line += "= x2paddle_nn.{}(".format(layer.kernel.split(":")[-1])
S
SunAhong1993 已提交
368 369
            else:
                line += " = {}(".format(layer.kernel)
J
jiangjiajun 已提交
370
            for k, v in layer.inputs.items():
S
SunAhong1993 已提交
371 372 373 374
                if isinstance(v, list):
                    line += "{}=[{}], ".format(k, ", ".join(v))
                else:
                    line += "{}={}, ".format(k, v)
J
jiangjiajun 已提交
375 376 377 378 379
            for k, v in layer.attrs.items():
                line += "{}={}, ".format(k, v)
            line = line.strip(", ")
            line += ")"
            write_code(f, [line], indent=1)
S
SunAhong1993 已提交
380 381 382 383 384 385 386

        write_code(
            f, [
                "return [{}], [{}]".format(", ".join(self.inputs),
                                           ", ".join(self.outputs))
            ],
            indent=1)
J
jiangjiajun 已提交
387 388
        f.close()

S
SunAhong1993 已提交
389 390

    def dump_parameter(self, param_name, param, save_dir):
S
SunAhong1993 已提交
391
        if not osp.exists(save_dir):
S
SunAhong1993 已提交
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
            os.makedirs(save_dir)
        dtype_map = {
            "int16": [framework_pb2.VarType.INT16, 'h'],
            "int32": [framework_pb2.VarType.INT32, 'i'],
            "int64": [framework_pb2.VarType.INT64, 'q'],
            "float16": [framework_pb2.VarType.FP16, 'e'],
            "float32": [framework_pb2.VarType.FP32, 'f'],
            "float64": [framework_pb2.VarType.FP64, 'd'],
            "bool": [framework_pb2.VarType.BOOL, None]
        }
        shape = param.shape
        if str(param.dtype) in ['uint8', 'uint_8', 'bool']:
            param = param.astype('int64')
        if len(shape) == 0:
            assert param.size == 1, "Unexpected situation happend!"
            shape = [1]
        assert str(
            param.dtype) in dtype_map, "Unknown dtype {} of params: {}.".format(
                str(param.dtype), param_name)
S
SunAhong1993 已提交
411
        fp = open(osp.join(save_dir, param_name), 'wb')
S
SunAhong1993 已提交
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
        numpy.array([0], dtype='int32').tofile(fp)
        numpy.array([0], dtype='int64').tofile(fp)
        numpy.array([0], dtype='int32').tofile(fp)
        tensor_desc = framework_pb2.VarType.TensorDesc()
        tensor_desc.data_type = dtype_map[str(param.dtype)][0]
        tensor_desc.dims.extend(shape)
        desc_size = tensor_desc.ByteSize()
        numpy.array([desc_size], dtype='int32').tofile(fp)
        fp.write(tensor_desc.SerializeToString())
        param.tofile(fp)
        fp.close()

    def get_dygraph_inputs(self):
        def update(layers):
            for layer_id, layer in layers.items():
                if self.edges_in.get(layer_id, 0) == 0 and self.edges_out.get(
                        layer_id, 0) == 0:
                    continue
S
SunAhong1993 已提交
430 431
                if layer.kernel == "paddle.to_tensor":
                    data = layer.attrs["data"]
S
SunAhong1993 已提交
432
                    self.inputs.append(data)
S
SunAhong1993 已提交
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
                if len(layer.blocks) > 0:
                    for block in layer.blocks:
                        block.get_dygraph_inputs()
                        self.inputs.extend(block.inputs)

        update(self.layers)
        self.inputs = list(set(self.inputs))
        if self.inputs is not None:
            self.inputs.sort()

    def get_dygraph_outputs(self):
        for layer_id, layer in self.layers.items():
            if self.edges_in.get(layer_id, 0) == 0 and self.edges_out.get(
                    layer_id, 0) == 0:
                continue
            if self.edges_out.get(layer_id, 0) == 0:
S
SunAhong1993 已提交
449 450
                
                for i, output_name in enumerate(layer.outputs):
S
SunAhong1993 已提交
451
                    if ("paddle.nn" in layer.kernel and "functional" not in layer.kernel):
S
SunAhong1993 已提交
452 453 454 455
                        if i == 0:
                            continue
                    if output_name not in self.outputs:
                        self.outputs.append(output_name)
S
SunAhong1993 已提交
456 457 458 459 460 461 462 463 464 465 466 467 468

    def gen_dygraph_code(self, code_dir=None, indent=2):
        def gen_codes(code_list, indent=0):
            indent_blank = "    " * indent
            codes = []
            for code_line in code_list:
                if code_line.strip() == "":
                    codes.append('\n')
                else:
                    codes.append(indent_blank + code_line + '\n')
            return codes

        def gen_head():
S
SunAhong1993 已提交
469 470 471
            if self.source_type == "caffe":
                custom_import = "from x2paddle.op_mapper.dygraph.caffe2paddle " + \
                                 "import caffe_custom_layer as x2paddle_nn"
S
SunAhong1993 已提交
472 473 474
            elif self.source_type == "pytorch":
                custom_import = "from x2paddle.op_mapper.dygraph.pytorch2paddle " + \
                                 "import pytorch_custom_layer as x2paddle_nn"
S
SunAhong1993 已提交
475 476
            else:
                custom_import = ""
S
SunAhong1993 已提交
477 478 479
            self.head = gen_codes(
                [
                    "import paddle",
S
SunAhong1993 已提交
480
                    "import math",
S
SunAhong1993 已提交
481
                    custom_import,
S
SunAhong1993 已提交
482
                    "",
S
SunAhong1993 已提交
483
                    "class {}(paddle.nn.Layer):".format(self.name),
S
SunAhong1993 已提交
484 485 486 487 488
                ],
                indent=0)
            input_data_name = ', '.join(self.inputs)
            self.init_func.extend(
                gen_codes(
S
SunAhong1993 已提交
489
                    ["def __init__(self):"], indent=1))
S
SunAhong1993 已提交
490 491 492 493 494 495 496
            self.init_func.extend(
                gen_codes(
                    ["super({}, self).__init__()".format(self.name)], indent=2))
            self.forward_func.extend(
                gen_codes(
                    ["def forward(self, {}):".format(input_data_name)],
                    indent=1))
S
SunAhong1993 已提交
497
            
S
SunAhong1993 已提交
498
        def gen_main_code(code_dir):
S
SunAhong1993 已提交
499 500 501 502
            input_data_name = ', '.join(self.inputs)
            self.run_func = gen_codes(
                [
                    "",
S
SunAhong1993 已提交
503
                    "def main({}):".format(input_data_name),
S
SunAhong1993 已提交
504 505
                ],
                indent=0)
S
SunAhong1993 已提交
506 507 508 509 510 511 512 513
            comment_list = list()
            comment_list.append("# 共{}个输入".format(len(self.inputs_info)))
            for k, v in self.inputs_info.items():
                comment_list.append("# {}: 形状为{},类型为{}。".format(k, v[0], v[1]))
            self.run_func.extend(
                gen_codes(
                    comment_list,
                    indent=1))
S
SunAhong1993 已提交
514
            use_structured_name = False if self.source_type in ["tf", "onnx"] else True
S
SunAhong1993 已提交
515 516
            self.run_func.extend(
                gen_codes(["paddle.disable_static()",
S
SunAhong1993 已提交
517
                           "params = paddle.load('{}/model.pdparams')".format(osp.abspath(code_dir)),
S
SunAhong1993 已提交
518
                           "model = {}()".format(self.name),
S
fix  
SunAhong1993 已提交
519
                           "model.set_dict(params, use_structured_name={})".format(use_structured_name),
S
SunAhong1993 已提交
520 521 522
                           "model.eval()",
                           "out = model({})".format(input_data_name),
                           "return out"], indent=1))
S
SunAhong1993 已提交
523 524

        def write_code(code_dir):
S
SunAhong1993 已提交
525
            f = open(osp.join(code_dir, 'x2paddle_code.py'), 'w')
S
SunAhong1993 已提交
526 527 528 529 530 531 532 533 534 535 536 537
            for code_line in self.head:
                f.write(code_line)
            init_writen_codes = []
            for code_line in self.init_func:
                if code_line in init_writen_codes:
                    continue
                f.write(code_line)
                init_writen_codes.append(code_line)
            f.write("\n")
            return_code = "return {}".format(", ".join(self.outputs))
            self.forward_func.extend(gen_codes([return_code], indent=2))
            for code_line in self.forward_func:
S
SunAhong1993 已提交
538 539
                if "assert [1, 1] == 1 or [1, 1] == [1, 1], 'The [1, 1] must be [1, [1, 1]]!'" in code_line:
                    continue
S
SunAhong1993 已提交
540
                f.write(code_line)
S
SunAhong1993 已提交
541 542
            for code_line in self.run_func:
                f.write(code_line)
S
SunAhong1993 已提交
543 544 545 546 547 548 549 550
            f.close()

        self.init_func = []
        self.forward_func = []
        if indent == 2 and code_dir is not None:
            gen_head()

        for layer_id, layer in self.layers.items():
S
SunAhong1993 已提交
551 552
            if layer.kernel.startswith("paddle"):
                remove_default_attrs(layer.kernel, layer.attrs)
S
SunAhong1993 已提交
553
            if ("paddle.nn" in layer.kernel and "functional" not in layer.kernel
S
SunAhong1993 已提交
554
                ) or layer.kernel == "paddle.to_tensor" or \
S
SunAhong1993 已提交
555 556
                layer.kernel.startswith("custom_layer") or \
                layer.kernel.startswith("paddle.fluid.dygraph"):
S
SunAhong1993 已提交
557 558
                line = "{}".format(
                    layer.outputs[0]
S
SunAhong1993 已提交
559 560
                ) if layer.kernel == "paddle.to_tensor" and not layer.attrs[
                    "data"].startswith("params[") else "self.{}".format(
S
SunAhong1993 已提交
561
                        layer.outputs[0])
S
SunAhong1993 已提交
562 563 564 565
                if layer.kernel.startswith("custom_layer"):
                    line += "= x2paddle_nn.{}(".format(layer.kernel.split(":")[-1])
                else:
                    line += " = {}(".format(layer.kernel)
S
SunAhong1993 已提交
566 567 568 569 570
                for k, v in layer.attrs.items():
                    line += "{}={}, ".format(k, v)
                line = line.strip(", ")
                line += ")"

S
SunAhong1993 已提交
571 572
                if layer.kernel == "paddle.to_tensor" and not layer.attrs[
                        "data"].startswith("params["):
S
SunAhong1993 已提交
573 574 575 576 577 578 579 580 581 582
                    self.forward_func.extend(gen_codes([line], indent=indent))
                    continue
                else:
                    self.init_func.extend(gen_codes([line], indent=2))

                if len(layer.outputs) == 1:
                    line = layer.outputs[0]
                elif len(layer.outputs) == 2:
                    line = layer.outputs[1]
                else:
S
SunAhong1993 已提交
583 584 585 586
                    if layer.kernel == "paddle.nn.LSTM":
                        line = "{}, ({})".format(layer.outputs[1], ', '.join(layer.outputs[-2:]))
                    else:
                        line = ','.join(layer.outputs[1:])
S
SunAhong1993 已提交
587 588
                if layer.kernel == "paddle.to_tensor" and layer.attrs[
                        "data"].startswith("params["):
S
SunAhong1993 已提交
589 590 591 592 593 594 595
                    line += " = self.{}".format(layer.outputs[0])
                else:
                    line += " = self.{}(".format(layer.outputs[0])
                    for k, v in layer.inputs.items():
                        line += "{}, ".format(v)
                    line = line.strip(", ")
                    line += ")"
S
SunAhong1993 已提交
596
                self.forward_func.extend(gen_codes([line], indent=indent))                
S
SunAhong1993 已提交
597 598
            elif "prim" in layer.kernel:
                func_name = layer.kernel.replace(".", "_")
S
SunAhong1993 已提交
599
                from x2paddle.op_mapper.dygraph.pytorch2paddle import prim2code
S
SunAhong1993 已提交
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
                if hasattr(prim2code, func_name):
                    func = getattr(prim2code, func_name)
                    func(
                        layer,
                        indent=indent,
                        init_func=self.init_func,
                        forward_func=self.forward_func)
                else:
                    raise Exception(
                        "The kind {} in paddle model is not supported yet.".
                        format(layer.kernel))
            else:
                if len(layer.outputs) == 1:
                    line = layer.outputs[0]
                else:
                    line = ','.join(layer.outputs)
                line += " = {}(".format(layer.kernel)
                for k, v in layer.inputs.items():
S
SunAhong1993 已提交
618 619
                    if isinstance(v, list):
                        line += "{}=[{}], ".format(k, ", ".join(v))
C
Channingss 已提交
620 621
                    elif isinstance(v, tuple):
                        line += "{}=({}), ".format(k, ", ".join(v))
S
SunAhong1993 已提交
622
                    else:
S
SunAhong1993 已提交
623 624 625 626
                        if k == "args":
                            line += v
                        else:
                            line += "{}={}, ".format(k, v)
S
SunAhong1993 已提交
627 628 629 630
                for k, v in layer.attrs.items():
                    line += "{}={}, ".format(k, v)
                line = line.strip(", ")
                line += ")"
S
SunAhong1993 已提交
631
                if layer.kernel == "self.create_parameter":
S
SunAhong1993 已提交
632
                    self.init_func.extend(gen_codes(["self." + line], indent=2))
S
SunAhong1993 已提交
633 634 635 636
                    self.forward_func.extend(gen_codes(["{} = self.{}".format(layer.outputs[0], 
                                                                              layer.outputs[0])], indent=indent))
                else:
                    self.forward_func.extend(gen_codes([line], indent=indent))
S
SunAhong1993 已提交
637
        if indent == 2 and code_dir is not None:
S
SunAhong1993 已提交
638
            gen_main_code(code_dir)
S
SunAhong1993 已提交
639 640 641 642 643
            write_code(code_dir)
        else:
            return self.init_func, self.forward_func

    def dump_dygraph_parameter(self, code_dir):
S
SunAhong1993 已提交
644
        save_path = osp.join(code_dir, 'model.pdparams')
S
SunAhong1993 已提交
645
        paddle.save(self.parameters, save_path)
J
jiangjiajun 已提交
646

S
SunAhong1993 已提交
647
    def dygraph2static(self, save_dir, input_shapes=[], input_types=[]):
S
SunAhong1993 已提交
648 649 650 651 652
        from paddle.fluid.dygraph.jit import declarative
        sepc_list = list()
        for i, name in enumerate(self.inputs):
            sepc_list.append(
                paddle.static.InputSpec(
S
SunAhong1993 已提交
653
                    shape=input_shapes[i], name=name, dtype=input_types[i]))
S
SunAhong1993 已提交
654 655 656 657
        import sys
        path = osp.abspath(save_dir)
        sys.path.insert(0, save_dir)
        import x2paddle_code
S
SunAhong1993 已提交
658
        paddle.disable_static()
S
SunAhong1993 已提交
659
        restore = paddle.load(osp.join(save_dir, "model.pdparams"))
S
SunAhong1993 已提交
660
        model = getattr(x2paddle_code, self.name)()
S
SunAhong1993 已提交
661
        if self.source_type in ["tf", "onnx"]:
S
SunAhong1993 已提交
662 663 664
            model.set_dict(restore, use_structured_name=False)
        else:
            model.set_dict(restore)
S
SunAhong1993 已提交
665 666
        model.eval()
        static_model = paddle.jit.to_static(model, input_spec=sepc_list)
S
SunAhong1993 已提交
667 668 669 670 671 672
        try:
            paddle.jit.save(static_model, osp.join(save_dir, "inference_model/model"))
        except ValueError as e:
            if str(e) == "'target_vars' should be a list of Variable.":
                print("[DyGraph2StaticGraph Error] Can not convert the dygraph to static! The output of PyTorch mustbe Variable or a list of Variable.")
            else:
S
SunAhong1993 已提交
673
                print(e)
S
fix  
SunAhong1993 已提交
674
                exit(0)