tf_op_mapper.py 47.7 KB
Newer Older
S
SunAhong1993 已提交
1
# Copyright (c) 2020  PaddlePaddle Authors. All Rights Reserved.
J
jiangjiajun 已提交
2 3 4 5 6 7 8 9 10 11 12 13
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
J
jiangjiajun 已提交
14

J
jiangjiajun 已提交
15
from x2paddle.decoder.tf_decoder import TFGraph
S
SunAhong1993 已提交
16
from x2paddle.core.program import PaddleGraph 
J
jiangjiajun 已提交
17
from x2paddle.core.op_mapper import OpMapper
J
jiangjiajun 已提交
18
from x2paddle.core.util import *
J
jiangjiajun 已提交
19 20 21
from x2paddle import program
import traceback
import math
J
jiangjiajun 已提交
22
import inspect
J
jiangjiajun 已提交
23
import numpy
J
jiangjiajun 已提交
24
import sys
25

J
jiangjiajun 已提交
26 27 28 29 30 31 32 33 34 35 36 37
name_counter = dict()


def gen_name(op_name, var_name):
    name = "{}_{}".format(op_name, var_name)
    if name not in name_counter:
        name_counter[name] = 0
    else:
        name_counter[name] += 1
    name = name + '_' + str(name_counter[name])
    return name

J
jiangjiajun 已提交
38

J
jiangjiajun 已提交
39 40 41 42
# 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 已提交
43 44
    if pad_size < 0:
        pad_size = 0
J
jiangjiajun 已提交
45 46 47 48
    pad0 = int(pad_size / 2)
    pad1 = pad_size - pad0
    return [pad0, pad1]

J
jiangjiajun 已提交
49

J
jiangjiajun 已提交
50
class TFOpMapper(OpMapper):
J
jiangjiajun 已提交
51 52 53 54 55 56
    directly_map_ops = {
        'Relu': ['relu'],
        'Relu6': ['relu6'],
        'Abs': ['abs'],
        'Sigmoid': ['sigmoid'],
        'Exp': ['exp'],
J
jiangjiajun 已提交
57
        'Rsqrt': ['rsqrt'],
J
jiangjiajun 已提交
58
        'Sqrt': ['sqrt'],
59
        'swish_f32': ['swish'],
J
jiangjiajun 已提交
60
        'Tanh': ['tanh'],
J
jiangjiajun 已提交
61
        'Softplus': ['softplus'],
62 63
        'LeakyRelu': ['leaky_relu', {
            'alpha': 'alpha'
J
jiangjiajun 已提交
64 65 66 67
        }],
        'Floor': ['floor'],
        'Erf': ['erf'],
        'Square': ['square']
J
jiangjiajun 已提交
68 69 70
    }
    elementwise_ops = {
        'Add': 'elementwise_add',
J
jiangjiajun 已提交
71
        'AddV2': 'elementwise_add',
J
jiangjiajun 已提交
72 73 74
        'RealDiv': 'elementwise_div',
        'Sub': 'elementwise_sub',
        'Maximum': 'elementwise_max',
J
jiangjiajun 已提交
75 76 77
        'Minimum': 'elementwise_min',
        'LessEqual': 'less_equal',
        'GreaterEqual': 'greater_equal',
78 79
        'Mul': 'elementwise_mul',
        'FloorDiv': 'elementwise_floordiv'
J
jiangjiajun 已提交
80 81
    }

J
jiangjiajun 已提交
82 83
    def __init__(self, decoder):
        super(TFOpMapper, self).__init__()
J
jiangjiajun 已提交
84
        self.decoder = decoder
J
jiangjiajun 已提交
85
        self.graph = decoder.tf_graph
S
SunAhong1993 已提交
86 87
        self.params = dict()
        self.paddle_graph = PaddleGraph(parent_layer=None, graph_type="static", source_type="tf")
88

J
jiangjiajun 已提交
89 90
        not_placeholder = list()
        for name in self.graph.input_nodes:
J
jiangjiajun 已提交
91 92 93 94 95
            if self.graph.get_node(
                    name).layer_type != "Placeholder" and self.graph.get_node(
                        name
                    ).layer_type != "OneShotIterator" and self.graph.get_node(
                        name).layer_type != "IteratorV2":
J
jiangjiajun 已提交
96 97 98 99
                not_placeholder.append(name)
        for name in not_placeholder:
            idx = self.graph.input_nodes.index(name)
            del self.graph.input_nodes[idx]
J
jiangjiajun 已提交
100

S
SunAhong1993 已提交
101 102
        self.paddle_graph.inputs = self.graph.input_nodes
        self.paddle_graph.outputs = self.graph.output_nodes
J
jiangjiajun 已提交
103

J
jiangjiajun 已提交
104
        unsupported_ops = set()
J
jiangjiajun 已提交
105
        sys.stderr.write("Total nodes: {}\n".format(len(self.graph.topo_sort)))
106
        for i, node_name in enumerate(self.graph.topo_sort):
J
jiangjiajun 已提交
107
            sys.stderr.write("\rConverting node {} ...     ".format(i + 1))
108 109
            node = self.graph.get_node(node_name)
            op = node.layer_type
J
jiangjiajun 已提交
110
            if op in self.directly_map_ops:
J
jiangjiajun 已提交
111 112
                if len(unsupported_ops) > 0:
                    continue
J
jiangjiajun 已提交
113 114
                self.directly_map(node)
            elif op in self.elementwise_ops:
J
jiangjiajun 已提交
115 116
                if len(unsupported_ops) > 0:
                    continue
J
jiangjiajun 已提交
117 118
                self.elementwise_map(node)
            elif hasattr(self, op):
J
jiangjiajun 已提交
119 120
                if len(unsupported_ops) > 0:
                    continue
J
jiangjiajun 已提交
121
                func = getattr(self, op)
J
jiangjiajun 已提交
122 123 124 125 126
                try:
                    func(node)
                except Exception as e:
                    unsupported_ops.add(op)
                    print("\n{}\n".format(traceback.format_exc()))
J
jiangjiajun 已提交
127
            else:
J
jiangjiajun 已提交
128 129
                unsupported_ops.add(op)
        if len(unsupported_ops) > 0:
J
jiangjiajun 已提交
130 131
            print("\n========= {} OPs are not supported yet ===========".format(
                len(unsupported_ops)))
J
jiangjiajun 已提交
132
            for op in unsupported_ops:
J
jiangjiajun 已提交
133
                print("========== {} ============".format(op))
J
jiangjiajun 已提交
134
            sys.exit(-1)
J
jiangjiajun 已提交
135
        sys.stderr.write("\nDone!\n")
S
SunAhong1993 已提交
136 137
        self.paddle_graph.set_name(self.graph.graph_name)
        self.paddle_graph.set_parameters(self.params)
J
jiangjiajun 已提交
138

J
jiangjiajun 已提交
139 140 141
    def directly_map(self, node):
        assert node.layer_type in self.directly_map_ops
        op_info = self.directly_map_ops[node.layer_type]
J
jiangjiajun 已提交
142
        input = self.graph.get_node(node.layer.input[0])
J
jiangjiajun 已提交
143 144 145 146 147 148
        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
J
jiangjiajun 已提交
149

S
SunAhong1993 已提交
150
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
151 152 153 154
            kernel="fluid.layers.{}".format(op_info[0]),
            inputs={"x": input.name},
            outputs=[node.name],
            **attr)
J
jiangjiajun 已提交
155 156 157 158

    def elementwise_map(self, node):
        assert node.layer_type in self.elementwise_ops
        op_type = self.elementwise_ops[node.layer_type]
J
jiangjiajun 已提交
159 160
        x = self.graph.get_node(node.layer.input[0])
        y = self.graph.get_node(node.layer.input[1])
J
jiangjiajun 已提交
161 162
        x_shape = x.out_shapes[0]
        y_shape = y.out_shapes[0]
S
SunAhong1993 已提交
163
        layer_id = self.paddle_graph.add_layer(
J
jiangjiajun 已提交
164 165 166 167
            kernel="fluid.layers.{}".format(op_type),
            inputs={"x": x.name,
                    "y": y.name},
            outputs=[node.name])
S
SunAhong1993 已提交
168
        self.paddle_graph.layers[layer_id].input_shapes = {"x": x_shape, "y": y_shape}
J
jiangjiajun 已提交
169 170 171 172 173

    def NotEqual(self, node):
        x = self.graph.get_node(node.layer.input[0])
        y = self.graph.get_node(node.layer.input[1])

S
SunAhong1993 已提交
174
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
175 176 177 178
            kernel="fluid.layers.not_equal",
            inputs={"x": x.name,
                    "y": y.name},
            outputs=[node.name])
J
jiangjiajun 已提交
179

180 181
    def Placeholder(self, node):
        shape = node.out_shapes[0]
J
jiangjiajun 已提交
182 183
        assert len(shape) != 0, "Unknown shape of input nodes[{}].".format(
            node.layer_name)
184
        dtype = node.dtype
S
SunAhong1993 已提交
185
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
186 187 188 189 190 191
            kernel="fluid.data",
            inputs={},
            outputs=[node.name],
            dtype=string(dtype),
            shape=shape,
            name=string(node.name))
J
jiangjiajun@baidu.com 已提交
192

J
jiangjiajun 已提交
193 194 195 196 197 198 199 200
    def Const(self, node):
        shape = node.out_shapes[0]
        dtype = node.dtype
        value = node.value
        initializer = "Constant(0.0)"
        if len(shape) == 0:
            assert value.size == 1, "Unexpected situation happend"
            shape = [1]
J
jiangjiajun 已提交
201 202
            if value == float('inf'):
                value = "float('inf')"
S
SunAhong1993 已提交
203
            self.paddle_graph.add_layer(
C
channingss 已提交
204 205 206 207 208 209 210
                kernel="fluid.layers.fill_constant",
                inputs={},
                outputs=[node.name],
                dtype=string(dtype),
                shape=[1],
                value=value)
            return
J
jiangjiajun 已提交
211

S
SunAhong1993 已提交
212 213
        self.params[node.name] = node.value
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
214 215 216 217 218 219 220
            kernel="fluid.layers.create_parameter",
            inputs={},
            outputs=[node.name],
            dtype=string(dtype),
            shape=shape,
            name=string(node.name),
            default_initializer=initializer)
J
jiangjiajun 已提交
221 222

    def Transpose(self, node):
J
jiangjiajun 已提交
223 224
        input = self.graph.get_node(node.layer.input[0])
        perm = self.graph.get_node(node.layer.input[1])
J
jiangjiajun 已提交
225
        assert perm.layer_type == "Const", "Perm of transpose OP should be Const"
J
jiangjiajun 已提交
226 227
        perm = perm.value.tolist()

S
SunAhong1993 已提交
228
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241
            kernel="fluid.layers.transpose",
            inputs={"x": input.name},
            outputs=[node.name],
            perm=perm)

    def Fill(self, node):
        dims = self.graph.get_node(node.layer.input[0])
        input_value = self.graph.get_node(node.layer.input[1])
        inputs = dict()
        attr = dict()
        assert input_value.layer_type == "Const", "Value of fill OP should be Const"
        if dims.layer_type == "Const":
            attr["shape"] = dims.value.tolist()
J
jiangjiajun 已提交
242
        else:
J
jiangjiajun 已提交
243 244 245
            inputs["shape"] = dims.name
        attr["dtype"] = string(input_value.dtype)
        attr["value"] = input_value.value
J
jiangjiajun 已提交
246

S
SunAhong1993 已提交
247
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
248 249 250 251
            "fluid.layers.fill_constant",
            inputs=inputs,
            outputs=[node.name],
            **attr)
J
jiangjiajun 已提交
252

J
jiangjiajun 已提交
253 254 255 256 257 258 259 260 261 262 263 264 265
    def DepthToSpace(self, node):
        input = self.graph.get_node(node.layer.input[0])

        block_size = node.get_attr("block_size")
        data_format = node.get_attr("data_format").decode()
        if data_format == "NHWC":
            n, h, w, c = input.out_shapes[0]
        else:
            n, c, h, w = input.out_shapes[0]

        input_name = input.name
        if data_format == "NHWC":
            transpose_name = gen_name("depth_to_space", "transpose")
S
SunAhong1993 已提交
266
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
267 268 269 270 271 272 273 274
                kernel="fluid.layers.transpose",
                inputs={"x": input.name},
                outputs=[transpose_name],
                perm=[0, 3, 1, 2])
            input_name = transpose_name

        shape = [0, block_size * block_size, -1, h, w]
        reshape_name = gen_name("depth_to_space", "reshape")
S
SunAhong1993 已提交
275
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
276 277 278 279 280 281
            kernel="fluid.layers.reshape",
            inputs={"x": input_name},
            outputs=[reshape_name],
            shape=shape)

        transpose_name = gen_name("depth_to_space", "transpose")
S
SunAhong1993 已提交
282
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
283 284 285 286 287 288
            kernel="fluid.layers.transpose",
            inputs={"x": reshape_name},
            outputs=[transpose_name],
            perm=[0, 2, 1, 3, 4])

        reshape_name = gen_name("depth_to_space", "reshape")
S
SunAhong1993 已提交
289
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
290 291 292 293 294
            kernel="fluid.layers.reshape",
            inputs={"x": transpose_name},
            outputs=[reshape_name],
            shape=[0, c, h, w])

S
SunAhong1993 已提交
295
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
296 297 298 299 300 301
            kernel="fluid.layers.pixel_shuffle",
            inputs={"x": reshape_name},
            outputs=[node.name],
            upscale_factor=block_size)

        if data_format == "NHWC":
S
SunAhong1993 已提交
302
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
303 304 305 306
                kernel="fluid.layers.transpose",
                inputs={"x": node.name},
                outputs=[node.name],
                perm=[0, 2, 3, 1])
S
add beg  
SunAhong1993 已提交
307 308 309 310 311 312 313 314 315
            
    def Neg(self, node):
        input = self.graph.get_input_node(node, 0)
        
        self.paddle_graph.add_layer(
            "paddle.scale",
            inputs={"x": input.name},
            outputs=[node.name],
            scale=-1)
J
jiangjiajun 已提交
316 317 318

    def MaxPool(self, node):
        input = self.graph.get_node(node.layer.input[0])
J
jiangjiajun 已提交
319

J
jiangjiajun 已提交
320 321 322 323 324
        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()

J
jiangjiajun 已提交
325 326 327
        input_name = input.name
        if data_format == "NHWC":
            transpose_name = gen_name("max_pool", "transpose")
S
SunAhong1993 已提交
328
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
329 330 331 332
                kernel="fluid.layers.transpose",
                inputs={"x": input.name},
                outputs=[transpose_name],
                perm=[0, 3, 1, 2])
J
jiangjiajun 已提交
333
            strides = [strides[i] for i in [0, 3, 1, 2]]
J
jiangjiajun 已提交
334
            k_size = [k_size[i] for i in [0, 3, 1, 2]]
J
jiangjiajun 已提交
335 336
            input_name = transpose_name

S
SunAhong1993 已提交
337
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
338 339 340 341 342 343 344 345 346
            kernel="fluid.layers.pool2d",
            inputs={"input": input_name},
            outputs=[node.name],
            pool_size=k_size[2:4],
            pool_type=string("max"),
            pool_stride=strides[2:4],
            pool_padding=string(pad_mode))

        if data_format == "NHWC":
S
SunAhong1993 已提交
347
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
348 349 350 351
                kernel="fluid.layers.transpose",
                inputs={"x": node.name},
                outputs=[node.name],
                perm=[0, 2, 3, 1])
J
jiangjiajun 已提交
352 353

    def Conv2D(self, node):
J
jiangjiajun 已提交
354 355
        input = self.graph.get_node(node.layer.input[0])
        kernel = self.graph.get_node(node.layer.input[1])
J
jiangjiajun 已提交
356

J
jiangjiajun 已提交
357 358 359 360 361
        k_size = kernel.out_shapes[0]
        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()
J
jiangjiajun 已提交
362 363 364 365
        if data_format == "NHWC":
            n, h, w, c = input.out_shapes[0]
        else:
            n, c, h, w = input.out_shapes[0]
J
jiangjiajun 已提交
366

J
jiangjiajun 已提交
367 368 369 370
        if kernel.layer_type == 'Const':
            kernel_value = kernel.value
            kernel_weight_name = kernel.name.replace('/', '_')
        else:
S
SunAhong1993 已提交
371
            kernel_value = self.decoder.infer_tensor(kernel, use_diff_inputs=False)
J
jiangjiajun 已提交
372 373 374 375 376
            if kernel.layer_type == 'Split':
                kernel_weight_name = "{}_{}_kernel".format(node.name,
                                                           kernel.name)
            else:
                kernel_weight_name = kernel.name.replace('/', '_')
S
SunAhong1993 已提交
377
        self.params[kernel_weight_name] = numpy.transpose(kernel_value,
J
jiangjiajun 已提交
378
                                                                 (3, 2, 0, 1))
J
jiangjiajun 已提交
379

J
jiangjiajun 已提交
380 381
        input_name = input.name
        if data_format == "NHWC":
J
jiangjiajun 已提交
382 383
            strides = [strides[i] for i in [0, 3, 1, 2]]
            dilations = [dilations[i] for i in [0, 3, 1, 2]]
J
jiangjiajun 已提交
384
            transpose_name = gen_name("conv2d", "transpose")
S
SunAhong1993 已提交
385
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
386 387 388 389 390 391 392 393 394 395
                kernel="fluid.layers.transpose",
                inputs={"x": input.name},
                outputs=[transpose_name],
                perm=[0, 3, 1, 2])
            input_name = transpose_name

        if c == -1:
            attr = {"shape": [0, k_size[2], 0, 0]}
            node.fluid_code.add_layer(
                "reshape", inputs=input, output=input, param_attr=attr)
S
SunAhong1993 已提交
396
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
397 398 399 400 401
                kernel="fluid.layers.reshape",
                inputs={"x": input_name},
                outputs=[input_name],
                shape=[0, k_size[2], 0, 0])

S
SunAhong1993 已提交
402
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
403 404 405 406 407 408 409 410 411 412 413 414
            kernel="fluid.layers.conv2d",
            inputs={"input": input_name},
            outputs=[node.name],
            bias_attr=False,
            param_attr=string(kernel_weight_name),
            num_filters=k_size[3],
            filter_size=k_size[0:2],
            stride=strides[2:4],
            dilation=dilations[2:4],
            padding=string(pad_mode))

        if data_format == "NHWC":
S
SunAhong1993 已提交
415
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
416 417 418 419
                kernel="fluid.layers.transpose",
                inputs={"x": node.name},
                outputs=[node.name],
                perm=[0, 2, 3, 1])
J
jiangjiajun 已提交
420

J
jiangjiajun 已提交
421
    def BiasAdd(self, node):
J
jiangjiajun 已提交
422 423
        input = self.graph.get_node(node.layer.input[0])
        bias = self.graph.get_node(node.layer.input[1])
S
SunAhong1993 已提交
424
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
425 426 427 428
            kernel="fluid.layers.elementwise_add",
            inputs={"x": input.name,
                    "y": bias.name},
            outputs=[node.name])
J
jiangjiajun 已提交
429 430

    def FusedBatchNorm(self, node):
J
jiangjiajun 已提交
431 432 433 434 435
        input = self.graph.get_node(node.layer.input[0])
        gamma = self.graph.get_node(node.layer.input[1])
        beta = self.graph.get_node(node.layer.input[2])
        moving_mean = self.graph.get_node(node.layer.input[3])
        moving_var = self.graph.get_node(node.layer.input[4])
J
jiangjiajun 已提交
436
        data_format = node.get_attr("data_format").decode()
J
jiangjiajun 已提交
437 438 439 440 441

        assert gamma.layer_type == "Const"
        assert beta.layer_type == "Const"
        assert moving_mean.layer_type == "Const"
        assert moving_var.layer_type == "Const"
J
jiangjiajun 已提交
442 443 444 445

        input_name = input.name
        if data_format == "NHWC":
            transpose_name = gen_name("batch_norm", "transpose")
S
SunAhong1993 已提交
446
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
447 448 449 450 451 452
                kernel="fluid.layers.transpose",
                inputs={"x": input.name},
                outputs=[transpose_name],
                perm=[0, 3, 1, 2])
            input_name = transpose_name

S
SunAhong1993 已提交
453
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
454 455 456 457 458 459 460 461 462 463 464
            kernel="fluid.layers.batch_norm",
            inputs={"input": input_name},
            outputs=[node.name],
            epsilon=node.get_attr("epsilon"),
            param_attr=string(gamma.name),
            bias_attr=string(beta.name),
            moving_mean_name=string(moving_mean.name),
            moving_variance_name=string(moving_var.name),
            is_test=True)

        if data_format == "NHWC":
S
SunAhong1993 已提交
465
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
466 467 468 469 470 471 472 473 474 475 476 477
                kernel="fluid.layers.transpose",
                inputs={"x": node.name},
                outputs=[node.name],
                perm=[0, 2, 3, 1])

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

S
SunAhong1993 已提交
478
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
479 480 481 482 483 484 485 486 487 488 489 490 491
            kernel="fluid.layers.reduce_mean",
            inputs={"input": input.name},
            outputs=[node.name],
            dim=dims,
            keep_dim=keep_dims)

    def Reshape(self, node):
        input = self.graph.get_node(node.layer.input[0])
        param = self.graph.get_node(node.layer.input[1])

        input_name = input.name
        if input.dtype == 'bool':
            cast_name = gen_name('reshape', 'cast')
S
SunAhong1993 已提交
492
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
493 494 495 496 497 498 499 500
                kernel="fluid.layers.cast",
                inputs={"x": input_name},
                outputs=[cast_name],
                dtype="'int32'")
            input_name = cast_name

        if param.layer_type == "Const":
            shape = param.value.tolist()
S
SunAhong1993 已提交
501
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
502 503 504 505 506
                kernel="fluid.layers.reshape",
                inputs={"x": input_name},
                outputs=[node.name],
                shape=shape)
        else:
S
SunAhong1993 已提交
507
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
508 509 510 511 512 513 514 515
                kernel="fluid.layers.reshape",
                inputs={"x": input_name,
                        "shape": param.name},
                outputs=[node.name])
        if param.layer_type != "Const":
            out_shape = numpy.array(node.out_shapes[0])
            if (out_shape > 0).any():
                out_shape[out_shape < 0] = 0
S
SunAhong1993 已提交
516
                self.paddle_graph.add_layer(
J
jiangjiajun 已提交
517 518 519 520 521 522
                    kernel="fluid.layers.reshape",
                    inputs={"x": node.name},
                    outputs=[node.name],
                    shape=out_shape.tolist())

        if input.dtype == 'bool':
S
SunAhong1993 已提交
523
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
                kernel="fluid.layers.cast",
                inputs={"x": node.name},
                outputs=[node.name],
                dtype="'bool'")

    def Pad(self, node):
        input = self.graph.get_node(node.layer.input[0])
        paddings = self.graph.get_node(node.layer.input[1])
        assert paddings.layer_type == "Const", "Padding should be Const"
        paddings = paddings.value.flatten().tolist()

        if len(input.out_shapes[0]) == 4:
            if paddings[0] + paddings[1] + paddings[6] + paddings[7] == 0:
                new_padding = paddings[2:6]
                transpose_name = gen_name("pad", "transpose")
S
SunAhong1993 已提交
539
                self.paddle_graph.add_layer(
J
jiangjiajun 已提交
540 541 542 543
                    kernel="fluid.layers.transpose",
                    inputs={"x": input.name},
                    outputs=[transpose_name],
                    perm=[0, 3, 1, 2])
S
SunAhong1993 已提交
544
                self.paddle_graph.add_layer(
J
jiangjiajun 已提交
545 546 547 548
                    kernel="fluid.layers.pad2d",
                    inputs={"input": transpose_name},
                    outputs=[node.name],
                    paddings=new_padding)
S
SunAhong1993 已提交
549
                self.paddle_graph.add_layer(
J
jiangjiajun 已提交
550 551 552 553 554 555
                    kernel="fluid.layers.transpose",
                    inputs={"x": node.name},
                    outputs=[node.name],
                    perm=[0, 2, 3, 1])
                return

S
SunAhong1993 已提交
556
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
557
            kernel="fluid.layers.pad",
S
SunAhong1993 已提交
558
            inputs={"x": input.name},
J
jiangjiajun 已提交
559 560 561 562 563 564
            outputs=[node.name],
            paddings=paddings)

    def Squeeze(self, node):
        input = self.graph.get_node(node.layer.input[0])
        squeeze_dims = node.get_attr('squeeze_dims')
S
SunAhong1993 已提交
565
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
566 567 568 569 570 571 572 573
            kernel="fluid.layers.squeeze",
            inputs={"input": input.name},
            outputs=[node.name],
            axes=squeeze_dims)

    def Softmax(self, node):
        input = self.graph.get_node(node.layer.input[0])
        axis = node.get_attr("axis")
S
SunAhong1993 已提交
574
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
575 576 577 578 579 580 581 582 583 584
            kernel="fluid.layers.softmax",
            inputs={"input": input.name},
            outputs=[node.name],
            axis=axis)

    def Shape(self, node):
        input = self.graph.get_node(node.layer.input[0])
        input_name = input.name
        if input.dtype == 'bool':
            cast_name = gen_name('shape', 'cast')
S
SunAhong1993 已提交
585
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
586 587 588 589 590
                kernel="fluid.layers.cast",
                inputs={"x": input.name},
                outputs=[cast_name],
                dtype="'int32'")
            input_name = cast_name
S
SunAhong1993 已提交
591
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
592 593 594 595 596 597 598 599 600
            kernel="fluid.layers.shape",
            inputs={"input": input_name},
            outputs=[node.name])

    def ArgMax(self, node):
        input = self.graph.get_node(node.layer.input[0])
        axis = self.graph.get_node(node.layer.input[1])
        assert axis.layer_type == "Const", "ArgMax only support Const parameter"
        axis = axis.value
S
SunAhong1993 已提交
601
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
602 603 604 605 606 607 608 609 610 611 612 613 614 615
            kernel="fluid.layers.argmax",
            inputs={"x": input.name},
            outputs=[node.name],
            axis=axis)

    def MatMul(self, node):
        x = self.graph.get_node(node.layer.input[0])
        y = self.graph.get_node(node.layer.input[1])
        transpose_a = node.get_attr('transpose_a')
        transpose_b = node.get_attr('transpose_b')
        if transpose_a is None:
            transpose_a = node.get_attr('adj_x')
        if transpose_b is None:
            transpose_b = node.get_attr('adj_y')
S
SunAhong1993 已提交
616
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
617 618 619 620 621 622 623 624 625 626 627 628
            kernel="fluid.layers.matmul",
            inputs={"x": x.name,
                    "y": y.name},
            outputs=[node.name],
            transpose_x=transpose_a,
            transpose_y=transpose_b)

    def BatchMatMul(self, node):
        return self.MatMul(node)

    def BatchMatMulV2(self, node):
        return self.MatMul(node)
J
jiangjiajun@baidu.com 已提交
629

J
jiangjiajun 已提交
630
    def DepthwiseConv2dNative(self, node):
J
jiangjiajun 已提交
631 632
        input = self.graph.get_node(node.layer.input[0])
        kernel = self.graph.get_node(node.layer.input[1])
J
jiangjiajun 已提交
633
        assert kernel.layer_type == "Const", "Kernel of DepthwiseConv2DNative should be Const"
J
jiangjiajun 已提交
634

J
jiangjiajun 已提交
635 636 637 638 639 640
        in_shape = input.out_shapes[0]
        k_size = kernel.out_shapes[0]
        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()
J
jiangjiajun 已提交
641

S
SunAhong1993 已提交
642
        self.params[kernel.layer_name.replace(
J
jiangjiajun 已提交
643
            '/', '_')] = numpy.transpose(kernel.value, (2, 3, 0, 1))
J
jiangjiajun 已提交
644

J
jiangjiajun 已提交
645 646
        input_name = input.name
        if data_format == "NHWC":
J
jiangjiajun 已提交
647 648 649
            in_shape = [in_shape[i] for i in [0, 3, 1, 2]]
            strides = [strides[i] for i in [0, 3, 1, 2]]
            dilations = [dilations[i] for i in [0, 3, 1, 2]]
J
jiangjiajun 已提交
650
            transpose_name = gen_name('depthwise_conv2d', 'transpose')
S
SunAhong1993 已提交
651
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
652 653 654 655 656 657
                kernel="fluid.layers.transpose",
                inputs={"x": input.name},
                outputs=[transpose_name],
                perm=[0, 3, 1, 2])
            input_name = transpose_name

S
SunAhong1993 已提交
658
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
659 660 661 662 663 664 665 666 667 668 669 670 671
            kernel="fluid.layers.conv2d",
            inputs={"input": input_name},
            outputs=[node.name],
            num_filters=in_shape[1],
            filter_size=k_size[0:2],
            stride=strides[2:4],
            dilation=dilations[2:4],
            groups=k_size[3] * in_shape[1],
            padding=string(pad_mode),
            param_attr=string(kernel.layer_name),
            bias_attr=False)

        if data_format == "NHWC":
S
SunAhong1993 已提交
672
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
673 674 675 676
                kernel="fluid.layers.transpose",
                inputs={"x": node.name},
                outputs=[node.name],
                perm=[0, 2, 3, 1])
J
jiangjiajun 已提交
677 678

    def AvgPool(self, node):
J
jiangjiajun 已提交
679
        input = self.graph.get_node(node.layer.input[0])
J
jiangjiajun 已提交
680

J
jiangjiajun 已提交
681 682 683 684 685
        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()

J
jiangjiajun 已提交
686 687 688
        input_name = input.name
        if data_format == "NHWC":
            transpose_name = gen_name("avg_pool", "transpose")
S
SunAhong1993 已提交
689
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
690 691 692 693
                kernel="fluid.layers.transpose",
                inputs={"x": input.name},
                outputs=[transpose_name],
                perm=[0, 3, 1, 2])
J
jiangjiajun 已提交
694
            strides = [strides[i] for i in [0, 3, 1, 2]]
J
jiangjiajun 已提交
695
            k_size = [k_size[i] for i in [0, 3, 1, 2]]
J
jiangjiajun 已提交
696 697
            input_name = transpose_name

S
SunAhong1993 已提交
698
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
699 700 701 702 703 704 705 706 707
            kernel="fluid.layers.pool2d",
            inputs={"input": input_name},
            outputs=[node.name],
            pool_size=k_size[2:4],
            pool_type=string("avg"),
            pool_stride=strides[2:4],
            pool_padding=string(pad_mode))

        if data_format == "NHWC":
S
SunAhong1993 已提交
708
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
709 710 711 712
                kernel="fluid.layers.transpose",
                inputs={"x": node.name},
                outputs=[node.name],
                perm=[0, 2, 3, 1])
J
jiangjiajun 已提交
713 714

    def Pack(self, node):
J
jiangjiajun 已提交
715 716
        inputs = [self.graph.get_node(name) for name in node.layer.input]
        input_names = [i.name for i in inputs]
J
jiangjiajun 已提交
717
        axis = node.get_attr("axis")
S
SunAhong1993 已提交
718
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
719 720 721 722 723
            kernel="fluid.layers.stack",
            inputs={"x": input_names},
            outputs=[node.name],
            axis=axis)
        if len(node.out_shapes[0]) == 1:
S
SunAhong1993 已提交
724
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
725 726 727 728 729 730 731 732 733 734 735 736 737
                kernel="fluid.layers.reshape",
                inputs={"x": node.name},
                outputs=[node.name],
                shape=[-1])

    def Unpack(self, node):
        input = self.graph.get_node(node.layer.input[0])
        axis = node.get_attr("axis")
        num = node.get_attr("num")
        shape = input.out_shapes[0]
        input_name = input.name
        if len(shape) == 1:
            if shape[0] > 0 and num == shape[0]:
S
SunAhong1993 已提交
738
                self.paddle_graph.add_layer(
J
jiangjiajun 已提交
739 740 741 742 743 744 745 746
                    kernel="fluid.layers.unsqueeze",
                    inputs={"input": input.name},
                    outputs=[node.name],
                    axes=[0])
                input_name = node.name
                axis = 1
            else:
                raise Exception("Unexpected situation happend in Unpack OP")
S
SunAhong1993 已提交
747
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
748 749 750 751 752
            kernel="fluid.layers.unstack",
            inputs={"x": input_name},
            outputs=["{}_p{}".format(node.layer_name, i) for i in range(num)],
            axis=axis,
            num=num)
J
jiangjiajun 已提交
753

J
jiangjiajun 已提交
754 755 756 757 758 759 760 761 762 763
    def ConcatV2(self, node):
        inputs = [self.graph.get_node(name) for name in node.layer.input[:-1]]
        axis = self.graph.get_node(node.layer.input[-1])
        assert axis.layer_type == "Const", "axis for ConcatV2 must be type Const"
        axis = axis.value
        if axis < 0:
            axis += len(inputs[0].out_shapes[0])

        input_names = [i.name for i in inputs]
        for i, ipt in enumerate(inputs):
J
jiangjiajun 已提交
764
            if ipt.dtype == 'bool':
J
jiangjiajun 已提交
765
                cast_name = gen_name('concat', 'cast')
S
SunAhong1993 已提交
766
                self.paddle_graph.add_layer(
J
jiangjiajun 已提交
767 768 769 770 771
                    kernel="fluid.layers.cast",
                    inputs={"x": ipt.name},
                    outputs=[cast_name],
                    dtype="'int32'")
                input_names[i] = cast_name
S
SunAhong1993 已提交
772
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
773 774 775 776 777
            kernel="fluid.layers.concat",
            inputs={"input": input_names},
            outputs=[node.name],
            axis=axis)
        if node.dtype == 'bool':
S
SunAhong1993 已提交
778
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
779 780 781 782
                kernel="fluid.layers.cast",
                inputs={"x": node.name},
                outputs=[node.name],
                dtype="'bool'")
J
jiangjiajun 已提交
783

J
jiangjiajun 已提交
784 785 786 787 788
    def StridedSlice(self, node):
        input = self.graph.get_node(node.layer.input[0])
        begin = self.graph.get_node(node.layer.input[1])
        end = self.graph.get_node(node.layer.input[2])
        strides = self.graph.get_node(node.layer.input[3])
J
jiangjiajun 已提交
789

J
jiangjiajun 已提交
790 791
        if strides.layer_type == "Const":
            strides = strides.value.tolist()
792
        else:
S
SunAhong1993 已提交
793
            strides = self.decoder.infer_tensor(strides)
J
jiangjiajun 已提交
794 795
        if begin.layer_type == "Const":
            begin = begin.value.tolist()
796
        else:
S
SunAhong1993 已提交
797
            begin = self.decoder.infer_tensor(begin)
J
jiangjiajun 已提交
798 799
        if end.layer_type == "Const":
            end = end.value.tolist()
800
        else:
S
SunAhong1993 已提交
801
            end = self.decoder.infer_tensor(end)
802

J
jiangjiajun 已提交
803 804
        assert len(set(strides)) == 1 and strides[
            0] == 1, "Only support strides be 1 in StridedSlice OP"
J
jiangjiajun 已提交
805

J
jiangjiajun 已提交
806 807 808 809
        if len(begin) < len(input.out_shapes[0]):
            begin = begin + [0] * (len(input.out_shapes[0]) - len(begin))
        if len(end) < len(input.out_shapes[0]):
            end = end + [0] * (len(input.out_shapes[0]) - len(end))
J
jiangjiajun 已提交
810 811 812 813
        for i in range(len(end)):
            if end[i] == 0:
                end[i] = 999999

J
jiangjiajun 已提交
814 815 816 817
        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')
J
jiangjiajun 已提交
818
        shrink_axis_mask = node.get_attr('shrink_axis_mask')
J
jiangjiajun 已提交
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850

        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])

S
SunAhong1993 已提交
851
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
852 853 854 855 856 857 858
            kernel="fluid.layers.slice",
            inputs={"input": input.name},
            outputs=[node.name],
            axes=[i for i in range(len(new_begin))],
            starts=new_begin,
            ends=new_end)
        if len(new_axes) > 0:
S
SunAhong1993 已提交
859
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
860 861 862 863 864 865 866 867
                kernel="fluid.layers.unsqueeze",
                inputs={"input": node.name},
                outputs=[node.name],
                axes=new_axes)
        if len(shrink_axes) > 0:
            if len(input.out_shapes[0]) + len(new_axes) <= 1:
                pass
            else:
S
SunAhong1993 已提交
868
                self.paddle_graph.add_layer(
J
jiangjiajun 已提交
869 870 871 872 873 874 875 876 877 878 879 880
                    kernel="fluid.layers.squeeze",
                    inputs={"input": node.name},
                    outputs=[node.name],
                    axes=shrink_axes)

    def Split(self, node):
        dim = self.graph.get_node(node.layer.input[0])
        input = self.graph.get_node(node.layer.input[1])
        assert dim.layer_type == "Const"
        num_split = node.get_attr('num_split')
        dim = dim.value

S
SunAhong1993 已提交
881
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
882 883 884 885 886 887 888
            kernel="fluid.layers.split",
            inputs={"input": input.name},
            outputs=[
                "{}_p{}".format(node.layer_name, i) for i in range(num_split)
            ],
            num_or_sections=num_split,
            dim=dim)
889 890

    def Slice(self, node):
J
jiangjiajun 已提交
891 892 893 894 895 896
        input = self.graph.get_node(node.layer.input[0])
        begin = self.graph.get_node(node.layer.input[1])
        size = self.graph.get_node(node.layer.input[2])

        inputs = {"x": input.name}
        attrs = {}
J
jiangjiajun 已提交
897 898
        if begin.layer_type == "Const":
            begin = begin.value.tolist()
J
jiangjiajun 已提交
899
            attrs['offsets'] = begin
J
jiangjiajun 已提交
900
        else:
J
jiangjiajun 已提交
901 902
            #             shape = begin.out_shapes[0]
            #             reshape_name = gen_name("slice", "reshape")
S
SunAhong1993 已提交
903
            #             self.paddle_graph.add_layer(
J
jiangjiajun 已提交
904 905 906 907 908
            #                 kernel="fluid.layers.reshape",
            #                 inputs={"x": begin.name},
            #                 outputs=[reshape_name],
            #                 shape=shape)
            #             inputs['offsets'] = reshape_name
S
SunAhong1993 已提交
909
            begin = self.decoder.infer_tensor(begin, use_diff_inputs=False).tolist()
J
jiangjiajun 已提交
910 911
            attrs['offsets'] = begin
        if size.layer_type == "Const":
J
jiangjiajun 已提交
912
            size = size.value.tolist()
J
jiangjiajun 已提交
913 914 915 916
            attrs['shape'] = size
        else:
            shape = size.out_shapes[0]
            reshape_name = gen_name("slice", "reshape")
S
SunAhong1993 已提交
917
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
918 919 920 921 922
                kernel="fluid.layers.reshape",
                inputs={"x": size.name},
                outputs=[reshape_name],
                shape=shape)
            inputs['shape'] = reshape_name
S
SunAhong1993 已提交
923
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
            kernel="fluid.layers.crop_tensor",
            inputs=inputs,
            outputs=[node.name],
            **attrs)

    def ResizeNearestNeighbor(self, node):
        input = self.graph.get_node(node.layer.input[0])
        resize_shape = self.graph.get_node(node.layer.input[1])
        data_format = "NHWC"
        inputs = {"input": input.name}
        attrs = {"align_corners": node.get_attr("align_corners")}

        if resize_shape.layer_type == "Const":
            resize_shape = resize_shape.value.tolist()
            attrs["out_shape"] = resize_shape
J
jiangjiajun 已提交
939
        else:
J
jiangjiajun 已提交
940 941
            shape = resize_shape.out_shapes[0]
            reshape_name = gen_name("resize_nearest", "reshape")
S
SunAhong1993 已提交
942
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
943 944 945 946 947 948 949 950
                kernel="fluid.layers.reshape",
                inputs={"x": resize_shape.name},
                outputs=[reshape_name],
                shape=shape)
            inputs["out_shape"] = reshape_name

        if data_format == "NHWC":
            transpose_name = gen_name("resize_nearest", "reshape")
S
SunAhong1993 已提交
951
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
952 953 954 955 956 957
                kernel="fluid.layers.transpose",
                inputs={"x": input.name},
                outputs=[transpose_name],
                perm=[0, 3, 1, 2])
            inputs["input"] = transpose_name

S
SunAhong1993 已提交
958
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
959 960 961 962 963 964
            kernel="fluid.layers.resize_nearest",
            inputs=inputs,
            outputs=[node.name],
            **attrs)

        if data_format == "NHWC":
S
SunAhong1993 已提交
965
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
966 967 968 969
                kernel="fluid.layers.transpose",
                inputs={"x": node.name},
                outputs=[node.name],
                perm=[0, 2, 3, 1])
970

J
jiangjiajun 已提交
971 972 973 974 975 976
    def ResizeBilinear(self, node):
        input = self.graph.get_node(node.layer.input[0])
        resize_shape = self.graph.get_node(node.layer.input[1])
        data_format = "NHWC"
        inputs = {"input": input.name}
        attrs = {"align_corners": node.get_attr("align_corners")}
J
jiangjiajun 已提交
977

J
jiangjiajun 已提交
978 979 980 981 982 983
        if resize_shape.layer_type == "Const":
            resize_shape = resize_shape.value.tolist()
            attrs["out_shape"] = resize_shape
        else:
            shape = resize_shape.out_shapes[0]
            reshape_name = gen_name("resize_bilinear", "reshape")
S
SunAhong1993 已提交
984
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
985 986 987 988 989 990 991 992
                kernel="fluid.layers.reshape",
                inputs={"x": resize_shape.name},
                outputs=[reshape_name],
                shape=shape)
            inputs["out_shape"] = reshape_name

        if data_format == "NHWC":
            transpose_name = gen_name("resize_bilinear", "reshape")
S
SunAhong1993 已提交
993
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
994 995 996 997 998 999
                kernel="fluid.layers.transpose",
                inputs={"x": input.name},
                outputs=[transpose_name],
                perm=[0, 3, 1, 2])
            inputs["input"] = transpose_name

S
SunAhong1993 已提交
1000
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1001 1002 1003 1004 1005 1006
            kernel="fluid.layers.resize_bilinear",
            inputs=inputs,
            outputs=[node.name],
            **attrs)

        if data_format == "NHWC":
S
SunAhong1993 已提交
1007
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1008 1009 1010 1011 1012 1013 1014 1015
                kernel="fluid.layers.transpose",
                inputs={"x": node.name},
                outputs=[node.name],
                perm=[0, 2, 3, 1])

    def Cast(self, node):
        input = self.graph.get_node(node.layer.input[0])
        dtype = node.dtype
S
SunAhong1993 已提交
1016
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
            kernel="fluid.layers.cast",
            inputs={"x": input.name},
            outputs=[node.name],
            dtype=string(dtype))

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

S
SunAhong1993 已提交
1029
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
            kernel="fluid.layers.reduce_sum",
            inputs={"input": input.name},
            outputs=[node.name],
            dim=dim,
            keep_dim=keep_dims)

    def Max(self, node):
        input = self.graph.get_node(node.layer.input[0])
        reduce_idx = self.graph.get_node(node.layer.input[1])
        assert reduce_idx.layer_type == "Const", "Only support Const parameter[reduce_idx]"
        keep_dims = node.get_attr("keep_dims")
        dim = reduce_idx.value.tolist()
S
SunAhong1993 已提交
1042
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1043 1044 1045 1046 1047
            kernel="fluid.layers.reduce_max",
            inputs={"input": input.name},
            outputs=[node.name],
            dim=dim,
            keep_dim=keep_dims)
1048

J
jiangjiajun 已提交
1049 1050 1051 1052
    def RandomUniform(self, node):
        shape = self.graph.get_node(node.layer.input[0])
        if shape.layer_type == "Const":
            shape = shape.value.tolist()
S
SunAhong1993 已提交
1053
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1054 1055 1056 1057 1058 1059 1060
                kernel="fluid.layers.uniform_random",
                inputs={},
                outputs=[node.name],
                shape=shape,
                min=0.0,
                max=0.9999)
        else:
S
SunAhong1993 已提交
1061
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1062 1063 1064 1065 1066
                kernel="fluid.layers.uniform_random",
                inputs={'shape': shape.name},
                outputs=[node.name],
                min=0.0,
                max=0.9999)
1067 1068

    def Conv2DBackpropInput(self, node):
J
jiangjiajun 已提交
1069 1070 1071
        out_shape = self.graph.get_node(node.layer.input[0])
        kernel = self.graph.get_node(node.layer.input[1])
        input = self.graph.get_node(node.layer.input[2])
1072

1073
        assert kernel.layer_type == "Const", "Kernel of Conv2DBackpropInput should be Const"
1074

J
jiangjiajun 已提交
1075 1076 1077
        if out_shape.layer_type == "Const":
            out_shape = out_shape.value.tolist()
        else:
S
SunAhong1993 已提交
1078 1079
            out_shape = self.decoder.infer_tensor(out_shape,
                                                  out_shape=node.out_shapes[0])
J
jiangjiajun 已提交
1080

1081
        in_shape = input.out_shapes[0]
J
jiangjiajun 已提交
1082
        if in_shape.count(-1) > 2:
S
SunAhong1993 已提交
1083
            in_shape = self.decoder.infer_tensor(input, use_diff_inputs=False).shape
1084
        k_size = kernel.out_shapes[0]
J
jiangjiajun 已提交
1085
        if k_size.count(-1) > 2:
S
SunAhong1993 已提交
1086
            k_size = self.decoder.infer_tensor(input, use_diff_inputs=False).shape
J
jiangjiajun 已提交
1087

J
jiangjiajun 已提交
1088
        pad_mode = node.get_attr("padding").decode()
1089 1090 1091
        strides = node.get_attr("strides")
        dilations = node.get_attr("dilations")
        data_format = node.get_attr("data_format").decode()
1092

S
SunAhong1993 已提交
1093
        self.params[kernel.layer_name.replace(
J
jiangjiajun 已提交
1094 1095 1096 1097
            '/', '_')] = numpy.transpose(kernel.value, (3, 2, 0, 1))

        input_name = input.name
        if data_format == "NHWC":
1098 1099 1100
            in_shape = [in_shape[i] for i in [0, 3, 1, 2]]
            strides = [strides[i] for i in [0, 3, 1, 2]]
            dilations = [dilations[i] for i in [0, 3, 1, 2]]
J
jiangjiajun 已提交
1101
            transpose_name = gen_name("conv2dbackpropinput", "transpose")
S
SunAhong1993 已提交
1102
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1103 1104 1105 1106 1107 1108
                kernel="fluid.layers.transpose",
                inputs={"x": input.name},
                outputs=[transpose_name],
                perm=[0, 3, 1, 2])
            input_name = transpose_name

S
SunAhong1993 已提交
1109
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
            kernel="fluid.layers.conv2d_transpose",
            inputs={"input": input_name},
            outputs=[node.name],
            bias_attr=False,
            param_attr=string(kernel.layer_name),
            num_filters=k_size[2],
            filter_size=k_size[0:2],
            stride=strides[2:4],
            dilation=dilations[2:4],
            padding=string(pad_mode),
            output_size=out_shape[1:3])

        if data_format == "NHWC":
S
SunAhong1993 已提交
1123
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1124 1125 1126 1127
                kernel="fluid.layers.transpose",
                inputs={"x": node.name},
                outputs=[node.name],
                perm=[0, 2, 3, 1])
1128

J
jiangjiajun 已提交
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
    def Tile(self, node):
        input = self.graph.get_node(node.layer.input[0])
        expand_times = self.graph.get_node(node.layer.input[1])
        inputs = {"x": input.name}
        attr = dict()
        if expand_times.layer_type == "Const":
            expand_times = expand_times.value.tolist()
            attr["expand_times"] = expand_times
        else:
            inputs["expand_times"] = expand_times.name
J
jiangjiajun 已提交
1139

S
SunAhong1993 已提交
1140
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1141 1142 1143 1144
            kernel="fluid.layers.expand",
            inputs=inputs,
            outputs=[node.name],
            **attr)
J
jiangjiajun 已提交
1145

J
jiangjiajun 已提交
1146 1147 1148 1149 1150 1151
    def Range(self, node):
        start = self.graph.get_node(node.layer.input[0])
        limit = self.graph.get_node(node.layer.input[1])
        delta = self.graph.get_node(node.layer.input[2])
        inputs = dict()
        attr = dict()
1152

C
channingss 已提交
1153 1154 1155
        dtype = 'int32'
        if start.dtype.startswith('float'):
            dtype = start.dtype
J
jiangjiajun 已提交
1156 1157
        if start.layer_type == "Const":
            attr["start"] = start.value
1158
        else:
J
jiangjiajun 已提交
1159
            inputs["start"] = start.name
C
channingss 已提交
1160 1161
        if limit.dtype.startswith('float'):
            dtype = limit.dtype
J
jiangjiajun 已提交
1162 1163
        if limit.layer_type == "Const":
            attr["end"] = limit.value
J
jiangjiajun 已提交
1164
        else:
J
jiangjiajun 已提交
1165
            inputs["end"] = limit.name
C
channingss 已提交
1166 1167
        if delta.dtype.startswith('float'):
            dtype = delta.dtype
J
jiangjiajun 已提交
1168 1169
        if delta.layer_type == "Const":
            attr["step"] = delta.value
J
jiangjiajun 已提交
1170
        else:
J
jiangjiajun 已提交
1171
            inputs["step"] = delta.name
C
channingss 已提交
1172
        node.set_dtype(dtype)
J
jiangjiajun 已提交
1173 1174
        attr["dtype"] = string(node.dtype)

S
SunAhong1993 已提交
1175
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1176 1177 1178 1179
            kernel="fluid.layers.range",
            inputs=inputs,
            outputs=[node.name],
            **attr)
J
jiangjiajun 已提交
1180 1181

    def SquaredDifference(self, node):
J
jiangjiajun 已提交
1182 1183 1184 1185 1186
        x = self.graph.get_node(node.layer.input[0])
        y = self.graph.get_node(node.layer.input[1])
        inputs = {"x": x.name, "y": y.name}
        x_shape = x.out_shapes[0]
        y_shape = y.out_shapes[0]
S
SunAhong1993 已提交
1187
        layer_id = self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1188
            "fluid.layers.elementwise_sub", inputs=inputs, outputs=[node.name])
S
SunAhong1993 已提交
1189
        self.paddle_graph.layers[layer_id].input_shapes = {"x": x_shape, "y": y_shape}
J
jiangjiajun 已提交
1190 1191 1192 1193

        inputs = {"x": node.name, "y": node.name}
        x_shape = node.out_shapes[0]
        y_shape = node.out_shapes[0]
S
SunAhong1993 已提交
1194
        layer_id = self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1195
            "fluid.layers.elementwise_mul", inputs=inputs, outputs=[node.name])
S
SunAhong1993 已提交
1196
        self.paddle_graph.layers[layer_id].input_shapes = {"x": x_shape, "y": y_shape}
J
jiangjiajun 已提交
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214

    def OneHot(self, node):
        input = self.graph.get_node(node.layer.input[0])
        depth = self.graph.get_node(node.layer.input[1])
        on_value = self.graph.get_node(node.layer.input[2])
        off_value = self.graph.get_node(node.layer.input[3])
        assert depth.layer_type == 'Const', 'Parameter depth should be Const in OneHot'
        assert on_value.layer_type == 'Const', 'Parameter on_value should be Const in OneHot'
        assert off_value.layer_type == 'Const', 'Parameter off_value should be Const in OneHot'

        attr = {'depth': depth.value}
        on_value = on_value.value
        off_value = off_value.value
        assert math.fabs(on_value -
                         1.0) < 1e-06, "on_value should be 1 in OneHot"
        assert math.fabs(off_value -
                         0.0) < 1e-06, "off_value should be 0 in OneHot"

S
SunAhong1993 已提交
1215
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
            "fluid.one_hot",
            inputs={"input": input.name},
            outputs=[node.name],
            depth=depth.value)

    def Pow(self, node):
        x = self.graph.get_node(node.layer.input[0])
        factor = self.graph.get_node(node.layer.input[1])
        inputs = {"x": x.name}
        attr = dict()
        if factor.layer_type == 'Const':
            attr["factor"] = factor.value.tolist()
        else:
            inputs["factor"] = factor.name
S
SunAhong1993 已提交
1230
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
            "fluid.layers.pow", inputs=inputs, outputs=[node.name], **attr)

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

J
jiangjiajun 已提交
1241 1242 1243
        input_name = input.name
        if input.dtype != "bool":
            input_name = gen_name("all", "cast")
S
SunAhong1993 已提交
1244
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1245 1246 1247 1248
                "fluid.layers.cast",
                inputs={"x": input.name},
                outputs=[input_name],
                dtype=string("bool"))
S
SunAhong1993 已提交
1249
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1250
            "fluid.layers.reduce_all",
J
jiangjiajun 已提交
1251
            inputs={"input": input_name},
J
jiangjiajun 已提交
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
            outputs=[node.name],
            **attr)

        node.layer.attr['dtype'].type = 10

    def GatherV2(self, node):
        embeddings = self.graph.get_node(node.layer.input[0])
        index = self.graph.get_node(node.layer.input[1])
        axis = self.graph.get_node(node.layer.input[2])
        assert axis.layer_type == 'Const', "Only support Const parameter[axis]"
        axis = axis.value.tolist()
        assert axis == 0, "Only support axis=0 in GatherV2 OP"
        index_name = index.name
        if len(index.out_shapes[0]) != 1:
            reshape_name = gen_name("gather", "reshape")
            index_name = reshape_name
S
SunAhong1993 已提交
1268
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1269 1270 1271 1272 1273
                "fluid.layers.reshape",
                inputs={"x": index.name},
                outputs=[reshape_name],
                shape=[-1])
        inputs = {'input': embeddings.name, 'index': index_name}
S
SunAhong1993 已提交
1274
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1275 1276 1277 1278 1279 1280
            "fluid.layers.gather",
            inputs=inputs,
            outputs=[node.name],
            overwrite=False)
        if len(index.out_shapes[0]) != 1:
            out_shape = node.out_shapes[0]
S
SunAhong1993 已提交
1281
            self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1282 1283 1284 1285 1286 1287
                kernel="fluid.layers.reshape",
                inputs={"x": node.name},
                outputs=[node.name],
                shape=out_shape)

    def ExpandDims(self, node):
J
jiangjiajun 已提交
1288 1289
        x = self.graph.get_node(node.layer.input[0], copy=True)
        y = self.graph.get_node(node.layer.input[1], copy=True)
J
jiangjiajun 已提交
1290 1291 1292 1293 1294 1295 1296 1297 1298
        inputs = {"input": x.name}
        attr = dict()
        if y.layer_type == 'Const':
            dim = y.value.tolist()
            if not isinstance(dim, list):
                dim = [dim]
            attr['axes'] = dim
        else:
            inputs['axes'] = y.name
S
SunAhong1993 已提交
1299
        self.paddle_graph.add_layer(
J
jiangjiajun 已提交
1300 1301 1302 1303
            "fluid.layers.unsqueeze",
            inputs=inputs,
            outputs=[node.name],
            **attr)