tf_op_mapper_nhwc.py 39.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   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.

J
jiangjiajun 已提交
15
from x2paddle.decoder.tf_decoder import TFGraph, TFGraphNode
16 17 18 19 20 21
from x2paddle.core.op_mapper import OpMapper
from x2paddle.core.util import *
import inspect
import numpy
import sys

J
jiangjiajun 已提交
22

23 24 25 26
# compute padding size for SAME mode
def get_same_padding(in_size, kernel_size, stride):
    new_size = int(math.ceil(in_size * 1.0 / stride))
    pad_size = (new_size - 1) * stride + kernel_size - in_size
J
jiangjiajun 已提交
27 28
    if pad_size < 0:
        pad_size = 0
29 30 31 32
    pad0 = int(pad_size / 2)
    pad1 = pad_size - pad0
    return [pad0, pad1]

J
jiangjiajun 已提交
33

J
jiangjiajun 已提交
34
def process_pack_shape(graph, param, shape_value):
J
jiangjiajun 已提交
35 36 37
    pack_inputs = [
        graph.get_node(name, copy=True) for name in param.layer.input
    ]
J
jiangjiajun 已提交
38 39 40 41 42 43 44 45 46 47 48
    all_const_value = 0
    for i in range(len(pack_inputs)):
        if pack_inputs[i].layer_type == "Const":
            pack_inputs[i] = pack_inputs[i].value
            all_const_value += 1
        elif shape_value[i] > 0:
            pack_inputs[i] = shape_value[i]
            all_const_value += 1
        else:
            if hasattr(pack_inputs[i], "index"):
                index = pack_inputs[i].index
J
jiangjiajun 已提交
49 50
                pack_inputs[i] = pack_inputs[i].layer_name + "[{}]".format(
                    index)
J
jiangjiajun 已提交
51 52
            else:
                pack_inputs[i] = pack_inputs[i].layer_name
J
jiangjiajun 已提交
53

J
jiangjiajun 已提交
54 55 56 57 58
    string_params = "["
    for i in range(len(pack_inputs)):
        string_params += "{}, ".format(pack_inputs[i])
    string_params = string_params.strip(", ") + "]"
    return string_params
59

J
jiangjiajun 已提交
60

61 62 63 64 65 66 67 68 69 70
class TFOpMapperNHWC(OpMapper):
    directly_map_ops = {
        'Relu': ['relu'],
        'Relu6': ['relu6'],
        'Shape': ['shape'],
        'Abs': ['abs'],
        'Sigmoid': ['sigmoid'],
        'Exp': ['exp'],
        'Rsqrt': ['rsqrt'],
        'swish_f32': ['swish'],
71
        'Tanh': ['tanh'],
72 73 74 75 76 77 78 79 80
        'LeakyRelu': ['leaky_relu', {
            'alpha': 'alpha'
        }]
    }
    elementwise_ops = {
        'Add': 'elementwise_add',
        'RealDiv': 'elementwise_div',
        'Sub': 'elementwise_sub',
        'Maximum': 'elementwise_max',
J
jiangjiajun 已提交
81 82
        'Mul': 'elementwise_mul',
        'FloorDiv': 'elementwise_floordiv'
83 84 85 86 87 88 89
    }

    def __init__(self, decoder):
        super(TFOpMapperNHWC, self).__init__()
        self.decoder = decoder
        self.graph = decoder.tf_graph
        self.weights = dict()
90
        self.batch_node = None
91 92 93 94 95 96 97 98 99 100 101 102
        self.omit_nodes = list()
        self.used_custom_layers = dict()

        not_placeholder = list()
        for name in self.graph.input_nodes:
            if self.graph.get_node(name).layer_type != "Placeholder":
                not_placeholder.append(name)
        for name in not_placeholder:
            idx = self.graph.input_nodes.index(name)
            del self.graph.input_nodes[idx]

        unsupported_ops = set()
103 104
        sys.stderr.write("Total nodes: {}\n".format(len(self.graph.topo_sort)))
        for i, node_name in enumerate(self.graph.topo_sort):
M
mamingjie-China 已提交
105
            sys.stderr.write("\rConverting node {} ...     ".format(i + 1))
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
            node = self.graph.get_node(node_name)
            op = node.layer_type
            if op in self.directly_map_ops:
                if len(unsupported_ops) > 0:
                    continue
                self.directly_map(node)
            elif op in self.elementwise_ops:
                if len(unsupported_ops) > 0:
                    continue
                self.elementwise_map(node)
            elif hasattr(self, op):
                if len(unsupported_ops) > 0:
                    continue
                func = getattr(self, op)
                func(node)
            else:
                unsupported_ops.add(op)
                continue
        if len(unsupported_ops) > 0:
            print("========= {} OPs are not supported yet ===========".format(
                len(unsupported_ops)))
            for op in unsupported_ops:
                print("========== {} ============".format(op))
            sys.exit(-1)
M
mamingjie-China 已提交
130
        sys.stderr.write("\nDone!\n")
131

J
jiangjiajun 已提交
132 133 134 135 136 137 138 139 140
    def add_omit_nodes(self, in_node_name, out_node_name):
        in_node = self.graph.get_node(in_node_name)
        out_node = self.graph.get_node(out_node_name)
        index = in_node.outputs.index(out_node_name)
        del in_node.outputs[index]
        index = out_node.inputs.index(in_node_name)
        del out_node.inputs[index]
        self.omit_nodes.append(in_node.layer_name)

141 142 143 144 145 146 147 148 149 150
    def directly_map(self, node):
        assert node.layer_type in self.directly_map_ops
        op_info = self.directly_map_ops[node.layer_type]
        input = self.graph.get_node(node.layer.input[0], copy=True)
        attr = dict()
        for param in op_info[1:]:
            tf_param_name = list(param.keys())[0]
            pd_param_name = list(param.values())[0]
            tf_param = node.get_attr(tf_param_name)
            attr[pd_param_name] = tf_param
M
modify  
mamingjie-China 已提交
151

J
jiangjiajun 已提交
152
        node.fluid_code.add_layer(op_info[0],
J
jiangjiajun 已提交
153 154 155
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)
156 157 158 159 160 161 162 163

    def elementwise_map(self, node):
        assert node.layer_type in self.elementwise_ops
        op_type = self.elementwise_ops[node.layer_type]
        x = self.graph.get_node(node.layer.input[0], copy=True)
        y = self.graph.get_node(node.layer.input[1], copy=True)
        x_shape = x.out_shapes[0]
        y_shape = y.out_shapes[0]
164 165 166 167
        if len(x_shape) == 0:
            x_shape = [1]
        if len(y_shape) == 0:
            y_shape = [1]
168 169 170 171 172 173 174 175 176 177 178 179
        # incomplement broadcasting support for paddle
        x_input = x
        y_input = y
        if len(x_shape) < len(y_shape):
            unrevertable_ops = [
                "elementwise_sub", "elementwise_div", "elementwise_floordiv",
                "elementwise_mod", "elementwise_pow"
            ]
            if op_type not in unrevertable_ops:
                x_input = y
                y_input = x
                x_shape = y.out_shapes[0]
M
modify  
mamingjie-China 已提交
180 181
                if len(x_shape) == 0:
                    x_shape = [1]
182
                y_shape = x.out_shapes[0]
M
modify  
mamingjie-China 已提交
183 184
                if len(y_shape) == 0:
                    y_shape = [1]
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
            else:
                raise Exception("Unexpected situation happend")

        if len(x_shape) == 4 and len(y_shape) == 1:
            inputs = {"x": x_input, "y": y_input}
            node.fluid_code.add_layer(op_type, inputs=inputs, output=node)
            return

        is_sub_seq = True
        for i in range(len(y_shape)):
            index = -1 * i - 1
            if y_shape[index] != x_shape[index]:
                is_sub_seq = False
        if not is_sub_seq:
            x_expand_times = [1] * len(x_shape)
            y_expand_times = [1] * len(y_shape)
            x_need_expand = False
            y_need_expand = False
            for i in range(len(y_shape)):
                index = -1 * i - 1
                if y_shape[index] != x_shape[index]:
                    if y_shape[index] == 1:
                        y_expand_times[index] = x_shape[index]
                        y_need_expand = True
                    elif x_shape[index] == 1:
                        x_expand_times[index] = y_shape[index]
                        x_need_expand = True
                    else:
                        raise Exception("Unexpected situation happend")
            if x_need_expand:
                attr = {"expand_times": x_expand_times}
                node.fluid_code.add_layer("expand",
                                          inputs=x_input,
                                          output="x_tmp",
                                          param_attr=attr)
                x_input = "x_tmp"
            if y_need_expand:
                attr = {"expand_times": y_expand_times}
                node.fluid_code.add_layer("expand",
                                          inputs=y_input,
                                          output="y_tmp",
                                          param_attr=attr)
                y_input = "y_tmp"
J
jiangjiajun 已提交
228 229 230 231 232
        inputs = {"x": x_input, "y": y_input}
        node.fluid_code.add_layer(op_type,
                                  inputs=inputs,
                                  output=node,
                                  param_attr=None)
233 234 235 236 237 238

    def Placeholder(self, node):
        shape = node.out_shapes[0]
        assert len(shape) != 0, "Unknown shape of input nodes[{}].".format(
            node.layer_name)
        dtype = node.dtype
J
jiangjiajun 已提交
239 240
        if shape[0] < 0:
            self.batch_node = node
241 242 243 244 245 246
        attr = {
            'dtype': string(dtype),
            'shape': shape,
            'name': string(node.layer_name),
            'append_batch_size': False
        }
J
jiangjiajun 已提交
247

248 249 250 251 252 253 254 255 256 257
        node.fluid_code.add_layer("data",
                                  inputs=None,
                                  output=node,
                                  param_attr=attr)

    def Const(self, node):
        shape = node.out_shapes[0]
        dtype = node.dtype
        value = node.value
        initializer = "Constant(0.0)"
J
jiangjiajun 已提交
258

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
        if len(shape) == 0:
            assert value.size == 1, "Unexpected situation happend"
            shape = [1]
            initializer = "Constant({})".format(value)

        self.weights[node.layer_name] = node.value

        attr = {
            'dtype': string(dtype),
            'shape': shape,
            'name': string(node.layer_name),
            'default_initializer': initializer
        }
        node.fluid_code.add_layer("create_parameter",
                                  inputs=None,
                                  output=node,
                                  param_attr=attr)

    def Transpose(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)
        perm = self.graph.get_node(node.layer.input[1], copy=True)
        assert perm.layer_type == "Const", "Perm of transpose OP should be Const"
        del self.weights[perm.layer_name.replace('/', '_')]
        perm.fluid_code.clear()
        perm = perm.value.tolist()

        attr = {'perm': perm}
        node.fluid_code.add_layer("transpose",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def MaxPool(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)

        k_size = node.get_attr("ksize")
        strides = node.get_attr("strides")
        data_format = node.get_attr("data_format").decode()
        pad_mode = node.get_attr("padding").decode()
        channel_first = data_format == "NCHW"

        attr = {
J
jiangjiajun 已提交
301
            "pool_size": k_size[1:3],
302
            "pool_type": string("max"),
J
jiangjiajun 已提交
303 304 305
            "pool_stride": strides[1:3],
            "pool_padding": string(pad_mode),
            "data_format": string("NHWC")
306
        }
J
jiangjiajun 已提交
307 308 309 310
        node.fluid_code.add_layer("pool2d",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)
311 312 313 314 315

    def Conv2D(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)
        kernel = self.graph.get_node(node.layer.input[1], copy=True)
        assert kernel.layer_type == "Const", "Kernel of Conv2D should be Const"
J
jiangjiajun 已提交
316
        self.add_omit_nodes(kernel.layer_name, node.layer_name)
317 318

        in_shape = input.out_shapes[0]
J
jiangjiajun 已提交
319
        if in_shape[3] < 0:
320 321
            in_shape = self.decoder.infer_tensor(input).shape
        k_size = kernel.out_shapes[0]
J
jiangjiajun 已提交
322
        if k_size.count(-1) > 0:
323 324 325 326 327 328 329 330 331 332 333 334 335 336
            k_size = self.decoder.infer_tensor(kernel).shape

        strides = node.get_attr("strides")
        dilations = node.get_attr("dilations")
        pad_mode = node.get_attr("padding").decode()

        self.weights[kernel.layer_name.replace('/', '_')] = numpy.transpose(
            kernel.value, (3, 2, 0, 1))

        attr = {
            "bias_attr": False,
            "param_attr": string(kernel.layer_name),
            "num_filters": k_size[3],
            "filter_size": k_size[0:2],
J
jiangjiajun 已提交
337 338 339 340
            "stride": strides[1:3],
            "dilation": dilations[1:3],
            "padding": string(pad_mode),
            "data_format": string("NHWC")
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
        }
        node.fluid_code.add_layer("conv2d",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def BiasAdd(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)
        bias = self.graph.get_node(node.layer.input[1], copy=True)
        inputs = {"x": input, "y": bias}
        node.fluid_code.add_layer("elementwise_add",
                                  inputs=inputs,
                                  output=node,
                                  param_attr=None)

    def FusedBatchNorm(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)
        gamma = self.graph.get_node(node.layer.input[1], copy=True)
        beta = self.graph.get_node(node.layer.input[2], copy=True)
        moving_mean = self.graph.get_node(node.layer.input[3], copy=True)
        moving_var = self.graph.get_node(node.layer.input[4], copy=True)

        assert gamma.layer_type == "Const"
        assert beta.layer_type == "Const"
        assert moving_mean.layer_type == "Const"
        assert moving_var.layer_type == "Const"
J
jiangjiajun 已提交
367 368 369 370
        self.add_omit_nodes(gamma.layer_name, node.layer_name)
        self.add_omit_nodes(beta.layer_name, node.layer_name)
        self.add_omit_nodes(moving_mean.layer_name, node.layer_name)
        self.add_omit_nodes(moving_var.layer_name, node.layer_name)
371 372 373 374 375 376 377

        attr = {
            "epsilon": node.get_attr("epsilon"),
            "param_attr": string(gamma.layer_name),
            "bias_attr": string(beta.layer_name),
            "moving_mean_name": string(moving_mean.layer_name),
            "moving_variance_name": string(moving_var.layer_name),
J
jiangjiajun 已提交
378 379
            "is_test": True,
            "data_layout": string("NHWC")
380 381 382 383 384 385 386 387 388 389 390
        }

        node.fluid_code.add_layer("batch_norm",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def DepthwiseConv2dNative(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)
        kernel = self.graph.get_node(node.layer.input[1], copy=True)
        assert kernel.layer_type == "Const", "Kernel of DepthwiseConv2DNative should be Const"
J
jiangjiajun 已提交
391
        self.add_omit_nodes(kernel.layer_name, node.layer_name)
392 393

        in_shape = input.out_shapes[0]
J
jiangjiajun 已提交
394
        if in_shape[3] < 0:
395 396
            in_shape = self.decoder.infer_tensor(input).shape
        k_size = kernel.out_shapes[0]
J
jiangjiajun 已提交
397
        if k_size.count(-1) > 0:
398 399 400 401 402 403 404 405 406 407 408 409 410 411
            k_size = self.decoder.infer_tensor(kernel).shape

        strides = node.get_attr("strides")
        dilations = node.get_attr("dilations")
        data_format = node.get_attr("data_format").decode()
        pad_mode = node.get_attr("padding").decode()
        channel_first = data_format == "NCHW"

        self.weights[kernel.layer_name.replace('/', '_')] = numpy.transpose(
            kernel.value, (2, 3, 0, 1))

        attr = {
            "bias_attr": False,
            "param_attr": string(kernel.layer_name),
J
jiangjiajun 已提交
412
            "num_filters": in_shape[3],
413
            "filter_size": k_size[0:2],
J
jiangjiajun 已提交
414 415 416
            "stride": strides[1:3],
            "dilation": dilations[1:3],
            "groups": k_size[3] * in_shape[3],
417
            "use_cudnn": False,
J
jiangjiajun 已提交
418 419
            "padding": string(pad_mode),
            "data_format": string("NHWC")
420 421 422 423 424 425 426 427 428
        }
        node.fluid_code.add_layer("conv2d",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def Reshape(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)
        param = self.graph.get_node(node.layer.input[1], copy=True)
J
jiangjiajun 已提交
429
        attr = None
430 431
        if param.layer_type == "Const":
            attr = {"shape": param.value.tolist()}
J
jiangjiajun 已提交
432
            inputs = {"x": input}
J
jiangjiajun 已提交
433
            self.add_omit_nodes(param.layer_name, node.layer_name)
434
        else:
J
jiangjiajun 已提交
435 436 437
            inputs = {"x": input, "shape": param}
            shape_value = self.decoder.infer_shape_tensor(param)
            if param.layer_type == "Pack":
J
jiangjiajun 已提交
438 439 440 441
                pack_inputs = [
                    self.graph.get_node(name, copy=True)
                    for name in param.layer.input
                ]
J
jiangjiajun 已提交
442 443 444 445 446 447 448 449 450 451 452
                all_const_value = 0
                for i in range(len(pack_inputs)):
                    if pack_inputs[i].layer_type == "Const":
                        pack_inputs[i] = pack_inputs[i].value
                        all_const_value += 1
                    elif shape_value[i] > 0:
                        pack_inputs[i] = shape_value[i]
                        all_const_value += 1
                    else:
                        if hasattr(pack_inputs[i], "index"):
                            index = pack_inputs[i].index
J
jiangjiajun 已提交
453 454
                            pack_inputs[i] = pack_inputs[
                                i].layer_name + "[{}]".format(index)
J
jiangjiajun 已提交
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
                        else:
                            pack_inputs[i] = pack_inputs[i].layer_name

                ### special optimize for paddle-lite
                in_size = 1
                in_shape = input.out_shapes[0]
                for i in range(len(in_shape)):
                    in_size *= in_shape[i]
                if all_const_value == len(pack_inputs) and in_size > 0:
                    if pack_inputs[0] > 0 and pack_inputs.count(-1) == 1:
                        for i in range(len(pack_inputs)):
                            in_size /= pack_inputs[i]
                        index = pack_inputs.index(-1)
                        pack_inputs[index] = in_size * -1
                        pack_inputs[0] = -1
J
jiangjiajun 已提交
470 471 472 473

                if all_const_value == len(pack_inputs) and pack_inputs.count(
                        -1) == 0:
                    pack_inputs[0] = -1
J
jiangjiajun 已提交
474 475 476 477 478 479 480
                ###################################

                string_params = "["
                for i in range(len(pack_inputs)):
                    string_params += "{}, ".format(pack_inputs[i])
                string_params = string_params.strip(", ") + "]"
                inputs["shape"] = string_params
J
jiangjiajun 已提交
481

482
        node.fluid_code.add_layer("reshape",
J
jiangjiajun 已提交
483
                                  inputs=inputs,
484 485 486 487 488 489 490 491 492 493 494
                                  output=node,
                                  param_attr=attr)

    def AvgPool(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)

        k_size = node.get_attr("ksize")
        strides = node.get_attr("strides")
        pad_mode = node.get_attr("padding").decode()

        attr = {
J
jiangjiajun 已提交
495
            "pool_size": k_size[1:3],
496
            "pool_type": string("avg"),
J
jiangjiajun 已提交
497 498 499
            "pool_stride": strides[1:3],
            "pool_padding": string(pad_mode),
            "data_format": string("NHWC")
500 501 502 503 504 505 506 507 508 509 510 511
        }
        node.fluid_code.add_layer("pool2d",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def SplitV(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)
        num_sections = self.graph.get_node(node.layer.input[1], copy=True)
        dim = self.graph.get_node(node.layer.input[2], copy=True)
        assert num_sections.layer_type == "Const"
        assert dim.layer_type == "Const"
J
jiangjiajun 已提交
512 513
        self.add_omit_nodes(num_sections.layer_name, node.layer_name)
        self.add_omit_nodes(dim.layer_name, node.layer_name)
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
        dim = dim.value
        attr = {
            "num_or_sections": num_sections.value.tolist(),
            "dim": dim.value
        }
        node.fluid_code.add_layer("split",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def ConcatV2(self, node):
        inputs = [
            self.graph.get_node(name, copy=True)
            for name in node.layer.input[:-1]
        ]
        axis = self.graph.get_node(node.layer.input[-1], copy=True)
        assert axis.layer_type == "Const"
J
jiangjiajun 已提交
531
        self.add_omit_nodes(axis.layer_name, node.layer_name)
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
        axis = axis.value
        if axis < 0:
            axis += len(inputs[0].out_shapes[0])

        attr = {"axis": axis}
        node.fluid_code.add_layer("concat",
                                  inputs=inputs,
                                  output=node,
                                  param_attr=attr)

    def Tile(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)
        expand_times = self.graph.get_node(node.layer.input[1], copy=True)
        if expand_times.layer_type == "Const":
            expand_times = expand_times.value.tolist()
J
jiangjiajun 已提交
547
            self.add_omit_nodes(expand_times.layer_name, node.layer_name)
548
        attr = {"expand_times": expand_times}
J
jiangjiajun 已提交
549 550 551 552
        node.fluid_code.add_layer("expand",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)
553 554 555 556 557

    def Pack(self, node):
        inputs = [
            self.graph.get_node(name, copy=True) for name in node.layer.input
        ]
J
jiangjiajun 已提交
558 559 560 561
        if len(inputs) == 1 and len(inputs[0].out_shapes[0]) == 0:
            input_name = inputs[0].layer_name
            if hasattr(inputs[0], "index"):
                input_name += "[{}]".format(inputs[0].index)
J
jiangjiajun 已提交
562 563
            node.fluid_code.add_note("{} = {}".format(node.layer_name,
                                                      input_name))
J
jiangjiajun 已提交
564
            return
565 566 567 568 569 570
        axis = node.get_attr("axis")
        attr = {"axis": axis}
        node.fluid_code.add_layer("stack",
                                  inputs=inputs,
                                  output=node,
                                  param_attr=attr)
J
jiangjiajun 已提交
571 572 573
        input_shape_sample = inputs[0].out_shapes[0]
        if len(input_shape_sample) == 0:
            attr = {"shape": [-1]}
J
jiangjiajun 已提交
574 575 576 577
            node.fluid_code.add_layer("reshape",
                                      inputs=node,
                                      output=node,
                                      param_attr=attr)
578 579 580 581 582

    def Pad(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)
        paddings = self.graph.get_node(node.layer.input[1], copy=True)
        assert paddings.layer_type == "Const", "Padding should be Const"
J
jiangjiajun 已提交
583
        self.add_omit_nodes(paddings.layer_name, node.layer_name)
584 585 586 587
        paddings = paddings.value.flatten().tolist()

        if len(input.out_shapes[0]) == 4:
            new_padding = None
J
jiangjiajun 已提交
588 589
            if paddings[0] + paddings[1] + paddings[6] + paddings[7] == 0:
                new_padding = paddings[2:6]
590
            if new_padding is not None:
J
jiangjiajun 已提交
591
                attr = {"paddings": new_padding, "data_format": string("NHWC")}
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
                node.fluid_code.add_layer("pad2d",
                                          inputs=input,
                                          output=node,
                                          param_attr=attr)
                return

        attr = {"paddings": paddings}
        node.fluid_code.add_layer("pad",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def Range(self, node):
        start = self.graph.get_node(node.layer.input[0], copy=True)
        limit = self.graph.get_node(node.layer.input[1], copy=True)
        delta = self.graph.get_node(node.layer.input[2], copy=True)
J
jiangjiajun 已提交
608
        all_param_const = -2
609
        if start.layer_type == "Const":
J
jiangjiajun 已提交
610
            self.add_omit_nodes(start.layer_name, node.layer_name)
611
            start = start.value
J
jiangjiajun 已提交
612
            all_param_const += 1
613
        if limit.layer_type == "Const":
J
jiangjiajun 已提交
614
            self.add_omit_nodes(limit.layer_name, node.layer_name)
615
            limit = limit.value
J
jiangjiajun 已提交
616
            all_param_const += 1
617
        if delta.layer_type == "Const":
J
jiangjiajun 已提交
618
            self.add_omit_nodes(delta.layer_name, node.layer_name)
619
            delta = delta.value
J
jiangjiajun 已提交
620
            all_param_const += 1
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
        dtype = node.dtype
        inputs = {
            "start": start,
            "end": limit,
            "step": delta,
            "dtype": string(dtype)
        }
        attr = {"dtype": string(node.dtype)}
        node.fluid_code.add_layer("range",
                                  inputs=inputs,
                                  output=node,
                                  param_attr=None)

    def Mean(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)
        reduce_idx = self.graph.get_node(node.layer.input[1], copy=True)
        assert reduce_idx.layer_type == "Const", "Only support Const parameter[reduce_idx]"
        dims = reduce_idx.value.tolist()
        keep_dims = node.get_attr("keep_dims")

        attr = {"dim": dims, "keep_dim": keep_dims}
        node.fluid_code.add_layer("reduce_mean",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def MatMul(self, node):
        x = self.graph.get_node(node.layer.input[0], copy=True)
        y = self.graph.get_node(node.layer.input[1], copy=True)
        transpose_a = node.get_attr('transpose_a')
        transpose_b = node.get_attr('transpose_b')
        inputs = {"x": x, "y": y}
        # fix paddle shape infer problem
        # should be removed after paddle 1.6
J
jiangjiajun 已提交
655 656 657 658 659 660
        x_last_dim = x.out_shapes[0][-1]
        y_last_dim = y.out_shapes[0][0]
        certain_dim = x_last_dim if x_last_dim > y_last_dim else y_last_dim
        shape = x.out_shapes[0]
        shape[-1] = certain_dim
        attr = {"shape": shape}
J
jiangjiajun 已提交
661 662 663 664
        node.fluid_code.add_layer("reshape",
                                  inputs=x,
                                  output=x,
                                  param_attr=attr)
J
jiangjiajun 已提交
665 666 667
        shape = y.out_shapes[0]
        shape[0] = certain_dim
        attr = {"shape": shape}
J
jiangjiajun 已提交
668 669 670 671
        node.fluid_code.add_layer("reshape",
                                  inputs=y,
                                  output=y,
                                  param_attr=attr)
J
jiangjiajun 已提交
672

673 674 675 676 677 678 679 680 681 682
        attr = {"transpose_x": transpose_a, "transpose_y": transpose_b}
        node.fluid_code.add_layer("matmul",
                                  inputs=inputs,
                                  output=node,
                                  param_attr=attr)

    def ArgMax(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)
        axis = self.graph.get_node(node.layer.input[1], copy=True)
        assert axis.layer_type == "Const", "ArgMax only support Const parameter"
J
jiangjiajun 已提交
683
        self.add_omit_nodes(axis.layer_name, node.layer_name)
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
        axis = axis.value
        attr = {"axis": axis}
        node.fluid_code.add_layer("argmax",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def StridedSlice(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)
        begin = self.graph.get_node(node.layer.input[1], copy=True)
        end = self.graph.get_node(node.layer.input[2], copy=True)
        strides = self.graph.get_node(node.layer.input[3], copy=True)
        assert begin.layer_type == "Const"
        assert end.layer_type == "Const"
        assert strides.layer_type == "Const"
J
jiangjiajun 已提交
699 700 701
        self.add_omit_nodes(begin.layer_name, node.layer_name)
        self.add_omit_nodes(end.layer_name, node.layer_name)
        self.add_omit_nodes(strides.layer_name, node.layer_name)
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
        strides = strides.value.tolist()
        assert len(set(strides)) == 1 and strides[
            0] == 1, "Only support strides be 1 in StridedSlice OP"

        begin = begin.value.tolist()
        end = end.value.tolist()

        for i in range(len(end)):
            if end[i] == 0:
                end[i] = 999999

        begin_mask = node.get_attr('begin_mask')
        end_mask = node.get_attr('end_mask')
        ellipsis_mask = node.get_attr('ellipsis_mask')
        new_axis_mask = node.get_attr('new_axis_mask')
        shrink_axis_mask = node.get_attr('shrink_axis_mask')

        assert ellipsis_mask == 0, "(OP:{} Name:{})Only support ellipsis_mask be 0[now: {}] n StridedSlice OP".format(
            node.layer_type, node.layer.name, ellipsis_mask)

        # TODO codes without validation
        # Use it carefully
        new_begin = list()
        new_end = list()
        new_axes = list()
        shrink_axes = list()
        for i, item in enumerate(begin):
            mask = (new_axis_mask >> i) & 1
            if mask != 0:
                new_axes.append(i)
                continue

            mask = (shrink_axis_mask >> i) & 1
            if mask != 0:
                shrink_axes.append(i)

            mask = (begin_mask >> i) & 1
            if mask != 0:
                new_begin.append(0)
            else:
                new_begin.append(item)

            mask = (end_mask >> i) & 1
            if mask != 0:
                new_end.append(999999)
            else:
                new_end.append(end[i])

        attr = {
            "axes": [i for i in range(len(new_begin))],
            "starts": new_begin,
            "ends": new_end
        }
        node.fluid_code.add_layer("slice",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)
        if len(new_axes) > 0:
            attr = {"axes": new_axes}
            node.fluid_code.add_layer("unsqueeze",
                                      inputs=node,
                                      output=node,
                                      param_attr=attr)
        if len(shrink_axes) > 0:
            if len(input.out_shapes[0]) + len(new_axes) <= 1:
                pass
            else:
                attr = {"axes": shrink_axes}
                node.fluid_code.add_layer("squeeze",
                                          inputs=node,
                                          output=node,
                                          param_attr=attr)

    def Slice(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)
        begin = self.graph.get_node(node.layer.input[1], copy=True)
        size = self.graph.get_node(node.layer.input[2], copy=True)
J
jiangjiajun 已提交
779 780
        attr = dict()
        inputs = {"x": input}
781
        if begin.layer_type == "Const":
J
jiangjiajun 已提交
782
            self.add_omit_nodes(begin.layer_name, node.layer_name)
783
            begin = begin.value.tolist()
J
jiangjiajun 已提交
784
            attr["offsets"] = begin
785
        else:
J
jiangjiajun 已提交
786 787 788
            inputs["offsets"] = begin
        if size.layer_type == "Const":
            self.add_omit_nodes(size.layer_name, node.layer_name)
789
            size = size.value.tolist()
J
jiangjiajun 已提交
790
            attr["shape"] = size
791
        else:
J
jiangjiajun 已提交
792
            inputs["shape"] = size
793

J
jiangjiajun 已提交
794
        if isinstance(begin, TFGraphNode) and begin.layer_type == "Pack":
J
jiangjiajun 已提交
795 796
            begin = process_pack_shape(self.graph, begin,
                                       self.decoder.infer_shape_tensor(begin))
J
jiangjiajun 已提交
797 798
            inputs["offsets"] = begin
        if isinstance(size, TFGraphNode) and size.layer_type == "Pack":
J
jiangjiajun 已提交
799 800
            size = process_pack_shape(self.graph, size,
                                      self.decoder.infer_shape_tensor(size))
J
jiangjiajun 已提交
801
            inputs["shape"] = size
802

J
jiangjiajun 已提交
803 804
        node.fluid_code.add_layer("crop_tensor",
                                  inputs=inputs,
805 806 807 808
                                  output=node,
                                  param_attr=attr)

    def Conv2DBackpropInput(self, node):
809
        out_shape = self.graph.get_node(node.layer.input[0], copy=True)
810
        kernel = self.graph.get_node(node.layer.input[1], copy=True)
811 812
        input = self.graph.get_node(node.layer.input[2], copy=True)

813
        assert kernel.layer_type == "Const", "Kernel of Conv2DBackpropInput should be Const"
814

J
jiangjiajun 已提交
815
        self.add_omit_nodes(kernel.layer_name, node.layer_name)
816
        self.add_omit_nodes(out_shape.layer_name, node.layer_name)
817

818 819 820
        if out_shape.layer_type == "Const":
            out_shape = out_shape.value.tolist()
        else:
J
jiangjiajun 已提交
821 822
            out_shape = self.decoder.infer_shape_tensor(out_shape,
                                                        node.out_shapes[0])
823

824
        in_shape = input.out_shapes[0]
J
jiangjiajun 已提交
825
        if in_shape[3] < 0:
826 827
            in_shape = self.decoder.infer_tensor(input).shape
        k_size = kernel.out_shapes[0]
J
jiangjiajun 已提交
828
        if k_size.count(-1) > 0:
829 830
            k_size = self.decoder.infer_tensor(kernel).shape

831
        pad_mode = node.get_attr("padding").decode()
832 833 834 835
        strides = node.get_attr("strides")
        dilations = node.get_attr("dilations")
        data_format = node.get_attr("data_format").decode()
        channel_first = data_format == "NCHW"
836

837 838
        self.weights[kernel.layer_name.replace('/', '_')] = numpy.transpose(
            kernel.value, (3, 2, 0, 1))
839

840 841 842
        attr = {
            "bias_attr": False,
            "param_attr": string(kernel.layer_name),
M
mamingjie-China 已提交
843
            "num_filters": k_size[2],
844
            "filter_size": k_size[0:2],
J
jiangjiajun 已提交
845 846
            "stride": strides[1:3],
            "dilation": dilations[1:3],
847
            "output_size": out_shape[1:3],
J
jiangjiajun 已提交
848 849
            "padding": string(pad_mode),
            "data_format": string("NHWC")
850 851 852 853 854
        }
        node.fluid_code.add_layer("conv2d_transpose",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)
855

856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
    def Max(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)
        reduce_idx = self.graph.get_node(node.layer.input[1], copy=True)
        assert reduce_idx.layer_type == "Const", "Only support Const parameter[reduce_idx]"
        keep_dims = node.get_attr("keep_dims")
        dim = reduce_idx.value.tolist()

        attr = {"dim": dim, "keep_dim": keep_dims}
        node.fluid_code.add_layer("reduce_max",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def Sum(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)
        reduce_idx = self.graph.get_node(node.layer.input[1], copy=True)
        assert reduce_idx.layer_type == "Const", "Only support Const parameter[reduce_idx]"
        keep_dims = node.get_attr("keep_dims")
        dim = reduce_idx.value.tolist()

        attr = {"dim": dim, "keep_dim": keep_dims}
        node.fluid_code.add_layer("reduce_sum",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def Cast(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)
        dtype = node.dtype_map[node.get_attr('DstT')]
        attr = {"dtype": string(dtype)}
        node.fluid_code.add_layer("cast",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def Split(self, node):
        dim = self.graph.get_node(node.layer.input[0], copy=True)
        input = self.graph.get_node(node.layer.input[1], copy=True)
        assert dim.layer_type == "Const"
J
jiangjiajun 已提交
895
        self.add_omit_nodes(dim.layer_name, node.layer_name)
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
        num_split = node.get_attr('num_split')
        dim = dim.value

        attr = {"num_or_sections": num_split, "dim": dim}
        node.fluid_code.add_layer("split",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def Squeeze(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)
        squeeze_dims = node.get_attr('squeeze_dims')
        attr = {"axes": squeeze_dims}
        node.fluid_code.add_layer("squeeze",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def Softmax(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)
        axis = node.get_attr("axis")
        attr = {"axis": axis}
        node.fluid_code.add_layer("softmax",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def ResizeNearestNeighbor(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)
        resize_shape = self.graph.get_node(node.layer.input[1], copy=True)
        if resize_shape.layer_type == "Const":
J
jiangjiajun 已提交
927
            self.add_omit_nodes(resize_shape.layer_name, node.layer_name)
928 929
            resize_shape = resize_shape.value.tolist()
        align_corners = node.get_attr("align_corners")
J
jiangjiajun 已提交
930 931 932 933 934
        attr = {
            "align_corners": align_corners,
            "out_shape": resize_shape,
            "data_format": string("NHWC")
        }
935
        node.fluid_code.add_layer("resize_nearest",
J
jiangjiajun 已提交
936
                                  inputs=input,
937 938 939 940 941 942 943
                                  output=node,
                                  param_attr=attr)

    def ResizeBilinear(self, node):
        input = self.graph.get_node(node.layer.input[0], copy=True)
        resize_shape = self.graph.get_node(node.layer.input[1], copy=True)
        if resize_shape.layer_type == "Const":
J
jiangjiajun 已提交
944
            self.add_omit_nodes(resize_shape.layer_name, node.layer_name)
945 946 947 948 949
            resize_shape = resize_shape.value.tolist()
        align_corners = node.get_attr("align_corners")
        attr = {
            "align_corners": align_corners,
            "out_shape": resize_shape,
J
jiangjiajun 已提交
950 951
            "align_mode": 1,
            "data_format": string("NHWC")
952 953
        }
        node.fluid_code.add_layer("resize_bilinear",
J
jiangjiajun 已提交
954
                                  inputs=input,
955 956
                                  output=node,
                                  param_attr=attr)
957 958 959 960 961 962 963 964 965 966 967 968 969

    def GreaterEqual(self, node):
        x = self.graph.get_node(node.layer.input[0], copy=True)
        y = self.graph.get_node(node.layer.input[1], copy=True)
        inputs = {"x": x, "y": y}
        node.fluid_code.add_layer("greater_equal",
                                  inputs=inputs,
                                  output=node,
                                  param_attr=None)

    def RandomUniform(self, node):
        shape = self.graph.get_node(node.layer.input[0], copy=True)
        if shape.layer_type == "Const":
J
jiangjiajun 已提交
970
            self.add_omit_nodes(shape.layer_name, node.layer_name)
971
            shape = shape.value.tolist()
J
jiangjiajun 已提交
972 973
        if not isinstance(shape, list):
            attr = {"dtype": string("int64")}
J
jiangjiajun 已提交
974 975 976 977
            node.fluid_code.add_layer("cast",
                                      inputs=shape,
                                      output=shape,
                                      param_attr=attr)
J
jiangjiajun 已提交
978 979 980 981 982 983
        attr = {"min": 0.0, "max": 0.9999}
        inputs = {"shape": shape}
        node.fluid_code.add_layer("uniform_random",
                                  inputs=inputs,
                                  output=node,
                                  param_attr=attr)
984 985 986 987 988 989 990 991 992 993 994 995 996 997

    def SquaredDifference(self, node):
        x = self.graph.get_node(node.layer.input[0], copy=True)
        y = self.graph.get_node(node.layer.input[1], copy=True)
        inputs = {"x": x, "y": y}
        node.fluid_code.add_layer("elementwise_sub",
                                  inputs=inputs,
                                  output=node,
                                  param_attr=None)
        inputs = {"x": node, "y": node}
        node.fluid_code.add_layer("elementwise_mul",
                                  inputs=inputs,
                                  output=node,
                                  param_attr=None)