program.py 18.4 KB
Newer Older
J
jiangjiajun 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#   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.

from __future__ import print_function
from __future__ import division
J
jiangjiajun 已提交
17
import paddle.fluid as fluid
S
SunAhong1993 已提交
18 19
import os.path as osp
import paddle
J
jiangjiajun 已提交
20
from paddle.fluid.proto import framework_pb2
J
jiangjiajun 已提交
21
from collections import OrderedDict
J
jiangjiajun 已提交
22
import numpy
J
jiangjiajun 已提交
23
import collections
J
jiangjiajun 已提交
24
import sys
J
jiangjiajun 已提交
25
import os
J
jiangjiajun 已提交
26
import six
S
SunAhong1993 已提交
27
import pickle
J
jiangjiajun 已提交
28 29 30


class PaddleLayer(object):
S
SunAhong1993 已提交
31
    def __init__(self, id, kernel, inputs, outputs, **kwargs):
J
jiangjiajun 已提交
32 33 34 35 36
        assert isinstance(
            inputs,
            dict), "parameter 'inputs' for PaddleLayer should be type of dict"
        assert isinstance(
            outputs,
J
jiangjiajun 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
            list), "parameter 'outputs' for PaddleLayer should be type of list"
        for k, v in inputs.items():
            if isinstance(v, list):
                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 已提交
52 53 54 55
        self.kernel = kernel
        self.inputs = inputs
        self.outputs = outputs
        self.attrs = kwargs
S
SunAhong1993 已提交
56 57
        self.id = id
        self.blocks = list()
J
jiangjiajun 已提交
58 59 60

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


S
SunAhong1993 已提交
63
class PaddleGraph(object):
S
SunAhong1993 已提交
64
    def __init__(self, parent_layer=None, graph_type="static"):
J
jiangjiajun 已提交
65
        self.layers = OrderedDict()
J
jiangjiajun 已提交
66 67 68 69 70
        self.edges_out = dict()
        self.edges_in = dict()
        self.inputs = list()
        self.outputs = list()
        self.parameters = dict()
S
SunAhong1993 已提交
71
        self.parent_layer = parent_layer
S
SunAhong1993 已提交
72
        self.graph_type = graph_type
S
SunAhong1993 已提交
73 74 75 76 77 78

    def set_name(self, name):
        self.name = name

    def set_parameters(self, parameters):
        self.parameters = parameters
J
jiangjiajun 已提交
79

J
jiangjiajun 已提交
80
    def clear(self):
J
jiangjiajun 已提交
81
        self.layers = OrderedDict()
J
jiangjiajun 已提交
82 83 84 85 86 87
        self.edges_out = dict()
        self.edges_in = dict()
        self.inputs = list()
        self.outputs = list()
        self.parameters = dict()

S
SunAhong1993 已提交
88 89 90 91
    def clear_edges(self):
        self.edges_out = dict()
        self.edges_in = dict()

J
jiangjiajun 已提交
92
    def add_layer(self, kernel, inputs, outputs, **kwargs):
J
jiangjiajun 已提交
93
        layer_id = str(len(self.layers))
S
SunAhong1993 已提交
94 95 96
        if self.parent_layer is not None:
            layer_id = "{}.{}.{}".format(self.parent_layer.id,
                                         len(self.parent_layer.blocks),
S
SunAhong1993 已提交
97 98
                                         layer_id)
        layer = PaddleLayer(layer_id, kernel, inputs, outputs, **kwargs)
J
jiangjiajun 已提交
99 100
        self.layers[layer_id] = layer
        return layer_id
J
jiangjiajun 已提交
101

S
SunAhong1993 已提交
102 103
    def build(self, inputs=None, outputs=None):
        self.clear_edges()
J
jiangjiajun 已提交
104
        outputs_from_nodes = dict()
J
jiangjiajun 已提交
105
        for layer_id, layer in self.layers.items():
J
jiangjiajun 已提交
106 107 108 109 110
            for input_key, input_var in layer.inputs.items():
                vs = input_var
                if not isinstance(vs, list):
                    vs = [vs]
                for v in vs:
S
SunAhong1993 已提交
111 112 113 114 115
                    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(
J
jiangjiajun 已提交
116
                        v)
S
SunAhong1993 已提交
117 118 119 120
                    if v in outputs_from_nodes:
                        in_layer_id = outputs_from_nodes[v]
                    else:
                        in_layer_id = -1
J
jiangjiajun 已提交
121 122 123 124 125 126 127
                    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 已提交
128
            for output in layer.outputs:
J
jiangjiajun 已提交
129
                outputs_from_nodes[output] = layer_id
J
jiangjiajun 已提交
130

S
SunAhong1993 已提交
131 132 133
            if len(layer.blocks) > 0:
                for block in layer.blocks:
                    block.build(layer.inputs, layer.outputs)
S
SunAhong1993 已提交
134

S
SunAhong1993 已提交
135 136
        if self.graph_type == "dygraph":
            self.get_dygraph_inputs()
S
SunAhong1993 已提交
137 138
            if len(self.outputs) == 0:
                self.get_dygraph_outputs()
S
SunAhong1993 已提交
139 140

    def get_global_layers(self):
S
SunAhong1993 已提交
141
        # 该全局layers的信息是按照拓扑排序组成的
S
SunAhong1993 已提交
142 143 144 145 146 147 148 149 150 151 152
        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)

J
jiangjiajun 已提交
153 154 155 156 157 158 159 160 161
    def gen_code(self, code_dir):
        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')

J
jiangjiajun 已提交
162 163 164
        if not os.path.exists(code_dir):
            os.makedirs(code_dir)
        f = open(os.path.join(code_dir, 'x2paddle_model.py'), 'w')
J
jiangjiajun 已提交
165 166 167 168 169

        write_code(
            f, [
                "from paddle.fluid.initializer import Constant",
                "from paddle.fluid.param_attr import ParamAttr",
S
SunAhong1993 已提交
170 171
                "import paddle.fluid as fluid", "import math", "",
                "def x2paddle_net():"
J
jiangjiajun 已提交
172 173
            ],
            indent=0)
J
jiangjiajun 已提交
174 175 176
        for layer_id, layer in self.layers.items():
            edges_in = self.edges_in.get(layer_id, [])
            edges_out = self.edges_out.get(layer_id, [])
J
jiangjiajun 已提交
177
            if len(edges_in) == 0 and len(edges_out) == 0:
J
jiangjiajun 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190
                continue

            line = ""

            if len(layer.outputs) == 1:
                line = layer.outputs[0]
            else:
                for output in layer.outputs:
                    line += "{}, ".format(output)
                line = line.strip(", ")

            line += " = {}(".format(layer.kernel)
            for k, v in layer.inputs.items():
J
jiangjiajun 已提交
191 192 193 194
                if isinstance(v, list):
                    line += "{}=[{}], ".format(k, ", ".join(v))
                else:
                    line += "{}={}, ".format(k, v)
J
jiangjiajun 已提交
195 196 197 198 199 200
            for k, v in layer.attrs.items():
                line += "{}={}, ".format(k, v)
            line = line.strip(", ")
            line += ")"
            write_code(f, [line], indent=1)

J
jiangjiajun 已提交
201 202 203 204 205 206 207
        write_code(
            f, [
                "return [{}], [{}]".format(", ".join(self.inputs),
                                           ", ".join(self.outputs))
            ],
            indent=1)
        f.close()
J
jiangjiajun 已提交
208

S
SunAhong1993 已提交
209
    def gen_model(self, save_dir, input_shapes):
S
SunAhong1993 已提交
210 211
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
S
SunAhong1993 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
        if self.graph_type == "static":
            code_dir = os.path.join(save_dir, 'model_with_code')
            infer_dir = os.path.join(save_dir, 'inference_model')
            self.gen_code(code_dir)
            sys.path.append(code_dir)
            import x2paddle_model
            scope = fluid.Scope()
            startup_program = fluid.Program()
            main_program = fluid.Program()
            with fluid.scope_guard(scope):
                with fluid.program_guard(main_program, startup_program):
                    inputs, outputs = x2paddle_model.x2paddle_net()
                    exe = fluid.Executor(fluid.CPUPlace())
                    exe.run(startup_program)

                    param_dir = os.path.join(code_dir, 'weights')
                    for k, v in self.parameters.items():
                        if scope.find_var(k):
                            self.dump_parameter(k, v, param_dir)

                    def if_exist(var):
                        b = os.path.exists(
                            os.path.join(os.path.join(param_dir, var.name)))
                        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)
        else:
            self.gen_dygraph_code(save_dir)
            self.dump_dygraph_parameter(save_dir)
S
SunAhong1993 已提交
247
            self.dygraph2static(save_dir, input_shapes)  #[[None, 3, 224, 224]]
J
jiangjiajun 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281

    def dump_parameter(self, param_name, param, save_dir):
        if not os.path.exists(save_dir):
            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)
        fp = open(os.path.join(save_dir, param_name), 'wb')
        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()
S
SunAhong1993 已提交
282

S
SunAhong1993 已提交
283 284 285 286 287 288 289 290 291 292 293 294 295 296
    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
                if layer.kernel == "fluid.dygraph.base.to_variable":
                    value = layer.attrs["value"]
                    if not value.startswith("params["):
                        self.inputs.append(value)
                if len(layer.blocks) > 0:
                    for block in layer.blocks:
                        block.get_dygraph_inputs()
                        self.inputs.extend(block.inputs)
S
SunAhong1993 已提交
297

S
SunAhong1993 已提交
298 299 300 301 302
        update(self.layers)
        self.inputs = list(set(self.inputs))

    def get_dygraph_outputs(self):
        for layer_id, layer in self.layers.items():
S
SunAhong1993 已提交
303 304 305 306 307
            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:
                for output_name in layer.outputs:
S
SunAhong1993 已提交
308
                    if not output_name.startswith("x"):
S
SunAhong1993 已提交
309 310
                        continue
                    self.outputs.append(output_name)
S
SunAhong1993 已提交
311
        self.outputs = list(set(self.outputs))
S
SunAhong1993 已提交
312 313

    def gen_dygraph_code(self, code_dir=None, indent=2):
S
SunAhong1993 已提交
314
        def gen_codes(code_list, indent=0):
S
SunAhong1993 已提交
315
            indent_blank = "    " * indent
S
SunAhong1993 已提交
316
            codes = []
S
SunAhong1993 已提交
317 318
            for code_line in code_list:
                if code_line.strip() == "":
S
SunAhong1993 已提交
319
                    codes.append('\n')
S
SunAhong1993 已提交
320
                else:
S
SunAhong1993 已提交
321 322
                    codes.append(indent_blank + code_line + '\n')
            return codes
S
SunAhong1993 已提交
323

S
SunAhong1993 已提交
324 325
        def gen_head():
            self.head = gen_codes(
S
SunAhong1993 已提交
326 327 328
                [
                    "from paddle.fluid.initializer import Constant",
                    "from paddle.fluid.param_attr import ParamAttr",
S
SunAhong1993 已提交
329
                    "import paddle",
S
SunAhong1993 已提交
330 331 332 333 334 335
                    "import paddle.fluid as fluid",
                    "",
                    "class {}(fluid.dygraph.Layer):".format(self.name),
                ],
                indent=0)
            input_data_name = ', '.join(self.inputs)
S
SunAhong1993 已提交
336 337
            self.init_func.extend(
                gen_codes(
S
SunAhong1993 已提交
338
                    ["def __init__(self, params):"], indent=1))
S
SunAhong1993 已提交
339 340
            self.init_func.extend(
                gen_codes(
S
SunAhong1993 已提交
341
                    ["super({}, self).__init__()".format(self.name)], indent=2))
S
SunAhong1993 已提交
342 343
            self.forward_func.extend(
                gen_codes(
S
SunAhong1993 已提交
344 345
                    ["def forward(self, {}):".format(input_data_name)],
                    indent=1))
S
SunAhong1993 已提交
346

S
SunAhong1993 已提交
347
        def write_code(code_dir):
S
SunAhong1993 已提交
348
            f = open(os.path.join(code_dir, 'x2paddle_code.py'), 'w')
S
SunAhong1993 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
            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:
                f.write(code_line)
            f.close()

        self.init_func = []
        self.forward_func = []
        if indent == 2 and code_dir is not None:
            gen_head()
S
SunAhong1993 已提交
368 369

        for layer_id, layer in self.layers.items():
S
SunAhong1993 已提交
370 371 372 373 374 375
            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":
                    continue
S
SunAhong1993 已提交
376
            if "paddle.nn" in layer.kernel or layer.kernel == "fluid.dygraph.base.to_variable":
S
SunAhong1993 已提交
377 378 379 380 381 382 383 384 385 386 387 388 389
                line = "{}".format(
                    layer.outputs[0]
                ) if layer.kernel == "fluid.dygraph.base.to_variable" and not layer.attrs[
                    "value"].startswith("params[") else "self.{}".format(
                        layer.outputs[0])
                line += " = {}(".format(layer.kernel)
                for k, v in layer.attrs.items():
                    line += "{}={}, ".format(k, v)
                line = line.strip(", ")
                line += ")"

                if layer.kernel == "fluid.dygraph.base.to_variable" and not layer.attrs[
                        "value"].startswith("params["):
S
SunAhong1993 已提交
390
                    self.forward_func.extend(gen_codes([line], indent=indent))
S
SunAhong1993 已提交
391 392
                    continue
                else:
S
SunAhong1993 已提交
393
                    self.init_func.extend(gen_codes([line], indent=2))
S
SunAhong1993 已提交
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409

                if len(layer.outputs) == 1:
                    line = layer.outputs[0]
                elif len(layer.outputs) == 2:
                    line = layer.outputs[1]
                else:
                    line = ','.join(layer.outputs[1:])
                if layer.kernel == "fluid.dygraph.base.to_variable" and layer.attrs[
                        "value"].startswith("params["):
                    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 已提交
410
                self.forward_func.extend(gen_codes([line], indent=indent))
S
SunAhong1993 已提交
411
            elif "prim" in layer.kernel:
S
SunAhong1993 已提交
412
                func_name = layer.kernel.replace(".", "_")
S
SunAhong1993 已提交
413 414 415
                from x2paddle.op_mapper.pytorch2paddle import prim2code
                if hasattr(prim2code, func_name):
                    func = getattr(prim2code, func_name)
S
SunAhong1993 已提交
416 417 418 419 420 421 422 423 424
                    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))
S
SunAhong1993 已提交
425 426 427 428 429 430 431 432 433 434 435 436
            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():
                    line += "{}={}, ".format(k, v)
                for k, v in layer.attrs.items():
                    line += "{}={}, ".format(k, v)
                line = line.strip(", ")
                line += ")"
S
SunAhong1993 已提交
437
                self.forward_func.extend(gen_codes([line], indent=indent))
S
SunAhong1993 已提交
438
        if indent == 2:
S
SunAhong1993 已提交
439
            write_code(code_dir)
S
SunAhong1993 已提交
440
        else:
S
SunAhong1993 已提交
441
            return self.init_func, self.forward_func
S
SunAhong1993 已提交
442 443 444 445 446

    def dump_dygraph_parameter(self, code_dir):
        params_output = open(os.path.join(code_dir, 'model.pdparams'), 'wb')
        pickle.dump(self.parameters, params_output)
        params_output.close()
S
SunAhong1993 已提交
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467

    def dygraph2static(self, save_dir, input_shapes=[]):
        from paddle.fluid.dygraph.jit import declarative
        sepc_list = list()
        for i, name in enumerate(self.inputs):
            sepc_list.append(
                paddle.static.InputSpec(
                    shape=input_shapes[i], name=name))
        import sys
        path = osp.abspath(save_dir)
        sys.path.insert(0, save_dir)
        import x2paddle_code
        place = fluid.CPUPlace()
        with fluid.dygraph.guard(place):
            restore, _ = fluid.load_dygraph(osp.join(save_dir, "model"))
            model = getattr(x2paddle_code, self.name)(restore)
            model.set_dict(restore)
            model.eval()
            model.forward = declarative(model.forward, sepc_list)
        fluid.dygraph.jit.save(
            layer=model, model_path=osp.join(save_dir, "inference"))