opset.py 62.5 KB
Newer Older
S
SunAhong1993 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
# Copyright (c) 2019  PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from x2paddle.decoder.onnx_decoder import ONNXGraph, ONNXGraphNode, ONNXGraphDataNode
from x2paddle.core.graph import GraphNode
from x2paddle.core.fluid_code import Layer
from x2paddle.core.fluid_code import FluidCode
from x2paddle.core.util import *
from functools import reduce
import numpy as np
import onnx
import onnx.numpy_helper as numpy_helper
from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE
import logging as _logging
from collections import OrderedDict
import math
import os
import copy
import sys
import shutil

_logger = _logging.getLogger(__name__)


def _const_weight_or_none(node, necessary=False):
    if 'Constant' in node.layer_type:
        return node.value
    if isinstance(node, ONNXGraphDataNode):
        return node.weight
    if necessary:
        assert '{} should be an initializer or Constant operator.'.format(
S
SunAhong1993 已提交
43
            node.name)
S
SunAhong1993 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
    return None


def _is_static_shape(shape):
    negtive_dims = 0
    error_dims = 0
    for dim in shape:
        if dim < 0:
            negtive_dims += 1
        if dim < -1:
            error_dims += 1
    if negtive_dims > 1:
        return False
    if error_dims > 0:
        return False
    return True


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
    pad0 = int(pad_size / 2)
    pad1 = pad_size - pad0
    return [pad0, pad1]


def print_mapping_info(func):
    def run_mapping(*args, **kwargs):
        node = args[1]
        try:
            res = func(*args, **kwargs)
        except:
            print("convert failed node:{}, op_type is {}".format(
S
SunAhong1993 已提交
77
                node.name[9:], node.layer_type))
S
SunAhong1993 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
            raise
        else:
            return res

    return run_mapping


class OpSet9():
    elementwise_ops = {
        'Add': 'paddle.add',
        'Div': 'paddle.divide',
        'Sub': 'fluid.layers.elementwise_sub',
        'Mul': 'paddle.multiply',
        'Pow': 'paddle.pow',
    }

S
SunAhong1993 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
    directly_map_ops = {
        'Ceil': ['paddle.ceil'],
        # reduce function
        'ReduceMean': ['paddle.mean',
                       dict(axes='axis', keepdims='keepdim'), 
                       dict(keepdims=1)],
        'ReduceSum': ['paddle.sum', 
                      dict(axes='axis', keepdims='keepdim'), 
                      dict(keepdims=1)],
        'ReduceMin': ['paddle.min', 
                      dict(axes='axis', keepdims='keepdim'), 
                      dict(keepdim=1)],
        'ReduceMax': ['paddle.max', 
                      dict(axes='axis', keepdims='keepdim'), 
                      dict(keepdim=1)],
        # active function
        'Relu': ['paddle.nn.ReLU'],
        'LeakyRelu': ['paddle.nn.LeakyReLU', 
                      dict(alpha='negative_slope'), 
S
SunAhong1993 已提交
113
                      dict(negative_slope=.01)],
S
SunAhong1993 已提交
114
        'Elu': ['paddle.nn.functional.elu', 
S
fix  
SunAhong1993 已提交
115
                dict(alpha='alpha'), 
S
SunAhong1993 已提交
116 117 118 119 120 121 122 123
                dict(alpha=1.)],
        'ThresholdedRelu': ['paddle.nn.functional.thresholded_relu', 
                            dict(alpha='threshold'),
                            dict(alpha=1.)],
        'Tanh': ['paddle.nn.Tanh'],
        'Sigmoid': ['paddle.nn.Sigmoid'],
        'Softsign': ['paddle.nn.Softsign'],
        'Softplus': ['paddle.nn.Softplus', 
S
fix  
SunAhong1993 已提交
124
                     dict(threshold='threshold'), 
S
SunAhong1993 已提交
125 126 127
                     dict(threshold=float(sys.maxsize))],
        'Exp': ['paddle.exp'],
        'Softmax': ['paddle.nn.Softmax', 
S
fix  
SunAhong1993 已提交
128
                    dict(axis='axis'), 
S
SunAhong1993 已提交
129 130 131 132 133
                    dict(axis=1)],
        'Sqrt': ['paddle.sqrt'],
        'Floor': ['paddle.floor'],
        'Abs': ['paddle.abs'],
        'Erf': ['paddle.erf'],
S
SunAhong1993 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
    }

    def __init__(self, decoder, paddle_graph):
        super(OpSet9, self).__init__()
        self.graph = decoder.graph
        self.paddle_graph = paddle_graph
        self.input_index = 0
        self.inputs_info = dict()
        self.weights = dict()
        self.nn_name2id = dict()

    @print_mapping_info
    def directly_map(self, node, *args, **kwargs):
        inputs = node.layer.input
        assert len(inputs) == 1, 'directly_map error with multi inputs'
        input = self.graph.get_input_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
        onnx_attrs = node.attr_map
        if '' in onnx_attrs:
            onnx_attrs.pop('')
        if '_' in onnx_attrs:
            onnx_attrs.pop('_')
        op_info = self.directly_map_ops[node.layer_type]
        paddle_op = op_info[0]
        layer_attrs = dict()
        if len(op_info) > 1:
            attrs_name_map_dict = op_info[1]
            for onnx_attr_name, pd_attr_name in attrs_name_map_dict.items():
                if onnx_attr_name in onnx_attrs:
                    layer_attrs[pd_attr_name] = onnx_attrs[onnx_attr_name]
                else:
                    layer_attrs[pd_attr_name] = op_info[2][onnx_attr_name]
S
SunAhong1993 已提交
165 166 167
        if paddle_op.startswith("paddle.nn"):
            op_name = paddle_op[10:].lower()
            op_name = name_generator(op_name, self.nn_name2id)
S
SunAhong1993 已提交
168
            output_name = node.name
S
SunAhong1993 已提交
169 170 171
            layer_outputs = [op_name, output_name]
            self.paddle_graph.add_layer(
                kernel=paddle_op,
S
SunAhong1993 已提交
172
                inputs={"x": input.name},
S
SunAhong1993 已提交
173 174 175 176 177
                outputs=layer_outputs,
                **layer_attrs)
        else:
            self.paddle_graph.add_layer(
                kernel=paddle_op,
S
SunAhong1993 已提交
178 179
                inputs={"x": input.name},
                outputs=[node.name],
S
SunAhong1993 已提交
180
                **layer_attrs)        
S
SunAhong1993 已提交
181
       
S
SunAhong1993 已提交
182 183 184 185 186 187
            
    @print_mapping_info
    def elementwise_map(self, node):
        op_type = self.elementwise_ops[node.layer_type]
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_y = self.graph.get_input_node(node, idx=1, copy=True)
S
SunAhong1993 已提交
188 189
        inputs_dict = {'x': val_x.name, 
                       'y': val_y.name}
S
SunAhong1993 已提交
190 191 192
        self.paddle_graph.add_layer(
            op_type, 
            inputs=inputs_dict, 
S
SunAhong1993 已提交
193
            outputs=[node.name])
S
SunAhong1993 已提交
194 195 196 197 198 199 200 201 202 203 204 205

    @print_mapping_info
    def place_holder(self, node):
        shape = node.out_shapes[0]
        for i, dim_shape in enumerate(shape):
            if dim_shape == 0 and i == 0:
                shape[i] = 1
            if dim_shape == 0 and i != 0:
                assert 'shape of input is not assigned'
        self.paddle_graph.add_layer(
            kernel="paddle.to_tensor",
            inputs={},
S
SunAhong1993 已提交
206
            outputs=[node.name],
S
SunAhong1993 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220
            data="x{}".format(self.input_index))
        self.inputs_info["x{}".format(self.input_index)] = [shape, node.dtype]
        self.input_index += 1

    @print_mapping_info
    def create_parameter(self, node, parameter=None):
        if parameter is not None:
            node = parameter
        dtype = node.dtype
        shape = node.out_shapes[0]
        if len(node.weight.shape) == 0:
            self.paddle_graph.add_layer(
                "paddle.full", 
                inputs={}, 
S
SunAhong1993 已提交
221
                outputs=[node.name],
S
SunAhong1993 已提交
222 223 224 225
                dtype=string(dtype),
                shape=[1],
                fill_value=node.weight)
        else:
S
SunAhong1993 已提交
226
            self.weights[node.name] = node.weight
S
SunAhong1993 已提交
227 228 229
            self.paddle_graph.add_layer(
                "self.create_parameter",
                inputs={},
S
SunAhong1993 已提交
230
                outputs=[node.name],
S
SunAhong1993 已提交
231
                shape=shape,
S
SunAhong1993 已提交
232
                attr=string(node.name),
S
SunAhong1993 已提交
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
                dtype=string(dtype),
                default_initializer="paddle.nn.initializer.Constant(value=0.0)")
        

    def _pad_if_asymmetric(self, node, pads, val_name):  # pads: SSEE
        assert len(pads) & 1 == 0
        symmetric = True
        ndims = len(pads) // 2
        for idx_dim in range(ndims):
            if pads[idx_dim] != pads[ndims + idx_dim]:
                symmetric = False
                break
        if symmetric:
            return pads[:ndims], val_name
        val_padded = self.Pad(node, op_independent=False)
        return [0] * ndims, val_padded

    def _interpolate(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
252
        inputs = {'x': val_x.name}
S
SunAhong1993 已提交
253
        attrs = dict()
S
SunAhong1993 已提交
254 255 256 257
        if node.layer_type == 'Resize':
            if len(node.layer.input) == 2:
                # opset 10
                val_scales = self.graph.get_input_node(node, idx=1, copy=True)
S
SunAhong1993 已提交
258
                inputs['scale_factor'] = val_scales.name
S
SunAhong1993 已提交
259 260 261
            elif len(node.layer.input) == 3:
                # opset 11
                val_scales = self.graph.get_input_node(node, idx=2, copy=True)
S
SunAhong1993 已提交
262
                attrs['scale_factor'] = self.weights[val_scales.name].tolist()[2:]
S
SunAhong1993 已提交
263 264 265
            elif len(node.layer.input) == 4:
                # opset 11
                val_sizes = self.graph.get_input_node(node, idx=3, copy=True)
S
SunAhong1993 已提交
266
                var_nc, var_hw = val_sizes.name + '_nc', val_sizes.name + '_hw'
S
SunAhong1993 已提交
267 268
                self.paddle_graph.add_layer(
                    'paddle.split',
S
SunAhong1993 已提交
269
                    inputs={"x": val_sizes.name},
S
SunAhong1993 已提交
270 271 272 273 274 275 276 277
                    outputs=[var_nc, var_hw],
                    num_or_sections=[2, 2],
                    axis=0)
                self.paddle_graph.add_layer(
                    "paddle.cast",
                    inputs={"x": var_hw},
                    outputs=[var_hw],
                    dtype=string('int32'))
S
SunAhong1993 已提交
278 279 280 281
#                 inputs['size'] = var_hw
                
                # TODO(syf): all use 
                inputs['out_shape'] = var_hw
S
fix  
SunAhong1993 已提交
282 283
                ipt = inputs.pop("x")
                inputs["input"] = ipt
S
SunAhong1993 已提交
284
                mode = node.get_attr('mode', 'nearest')
S
SunAhong1993 已提交
285
                attrs.update({"align_corners": False})
S
SunAhong1993 已提交
286 287 288
                self.paddle_graph.add_layer(
                    kernel="fluid.layers.resize_nearest",
                    inputs=inputs,
S
SunAhong1993 已提交
289
                    outputs=[node.name],
S
SunAhong1993 已提交
290 291
                    **attrs)
                return
S
SunAhong1993 已提交
292 293 294 295 296
        elif node.layer_type == 'Upsample':
            val_scales = self.graph.get_input_node(node, idx=1, copy=True)
            inputs['scale'] = val_scales

        mode = node.get_attr('mode', 'nearest')
S
SunAhong1993 已提交
297 298 299
        attrs.update({"align_corners": False,
                      "mode": string(mode),
                      "align_mode": 1})
S
SunAhong1993 已提交
300 301 302
        self.paddle_graph.add_layer(
            kernel="paddle.nn.functional.interpolate",
            inputs=inputs,
S
SunAhong1993 已提交
303
            outputs=[node.name],
S
SunAhong1993 已提交
304 305 306 307 308 309 310 311 312
            **attrs)
        
    @print_mapping_info
    def HardSigmoid(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        alpha = node.get_attr('alpha', 0.2)
        beta = node.get_attr('beta', 0.5)
        self.paddle_graph.add_layer(
            kernel="paddle.scale",
S
SunAhong1993 已提交
313 314
            inputs={"x": val_x.name},
            outputs=[node.name + "_val"],
S
SunAhong1993 已提交
315 316 317 318
            scale=alpha,
            bias=beta)
        self.paddle_graph.add_layer(
            kernel="paddle.clip",
S
SunAhong1993 已提交
319 320
            inputs={"x": node.name + "_val"},
            outputs=[node.name],
S
SunAhong1993 已提交
321
            min=0.0,
S
SunAhong1993 已提交
322 323 324 325 326 327 328 329 330 331 332 333 334 335
            max=1.0)  
        
    @print_mapping_info
    def Shape(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        self.paddle_graph.add_layer(
            kernel="paddle.shape",
            inputs={"input": val_x.name},
            outputs=[node.name])
        self.paddle_graph.add_layer(
                'paddle.cast',
                inputs={"x": node.name},
                outputs=[node.name],
                dtype=string('int64'))   
S
SunAhong1993 已提交
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353

    @print_mapping_info
    def RoiAlign(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_rois = self.graph.get_input_node(node, idx=1, copy=True)

        pooled_height = node.get_attr('output_height')
        pooled_width = node.get_attr('output_width')
        spatial_scale = node.get_attr('spatial_scale')
        sampling_ratio = node.get_attr('sampling_ratio')
        layer_attrs = {
            'pooled_height': pooled_height,
            'pooled_width': pooled_width,
            'spatial_scale': spatial_scale,
            'sampling_ratio': sampling_ratio,
        }
        self.paddle_graph.add_layer(
            'fluid.layers.roi_align',
S
SunAhong1993 已提交
354 355 356
            inputs={'input': val_x.name,
                    'rois': val_rois.name},
            outputs=[node.name],
S
SunAhong1993 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
            **layer_attrs)
                       

    @print_mapping_info
    def MaxRoiPool(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_rois = self.graph.get_input_node(node, idx=1, copy=True)

        spatial_scale = node.get_attr('spatial_scale')
        pooled_height, pooled_width = node.get_attr('pooled_shape')
        layer_attrs = {
            'pooled_height': pooled_height,
            'pooled_width': pooled_width,
            'spatial_scale': spatial_scale,
        }
        self.paddle_graph.add_layer(
            'fluid.layers.roi_pool',
S
SunAhong1993 已提交
374 375 376
            inputs={'input': val_x.name,
                    'rois': val_rois.name},
            outputs=[node.name],
S
SunAhong1993 已提交
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
            **layer_attrs)

    @print_mapping_info
    def Pad(self, node, op_independent=True):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        pads = node.get_attr('pads')
        mode = node.get_attr('mode', 'constant')
        value = node.get_attr('value', 0.)
        data_shape = val_x.out_shapes[0]
        output_shape = node.out_shapes[0]
        assume_pad2d = False
        layer_attrs = {}
        layer_attrs['mode'] = string(mode)
        paddings = []
        if len(pads) == 4:
            assume_pad2d |= mode != 'constant'
            if data_shape:
                assume_pad2d |= data_shape and len(data_shape) == 4  # NCHW
            if output_shape:
                assume_pad2d |= output_shape and len(output_shape) == 4  # NCHW
        if assume_pad2d:
            paddle_op = 'paddle.nn.Pad2D'
            layer_attrs['data_format'] = string('NCHW')
            layer_attrs['value'] = value
        else:
            paddle_op = 'fluid.layers.pad'
            layer_attrs["pad_value"] = value
        if len(pads) == 4:
            paddings = np.array(pads).reshape(
                (-1, 2)).transpose().flatten().tolist()  # SSEE -> SESE
        elif len(pads) == 8:
            paddings = np.array(pads).reshape(
                (-1, 4)).transpose().flatten().tolist()  # SSEE -> SESE
            if sum(paddings[:4]) == 0:
                paddle_op = 'paddle.nn.Pad2D'
                paddings = paddings[4:]
                layer_attrs['value'] = value
                if 'pad_value' in layer_attrs:
                    layer_attrs.pop('pad_value')
        tmp_paddings = copy.deepcopy(paddings)
        paddings[0] = tmp_paddings[2]
        paddings[1] = tmp_paddings[3]
        paddings[2] = tmp_paddings[0]
        paddings[3] = tmp_paddings[1]
        if paddle_op == 'paddle.nn.Pad2D':
            layer_attrs['padding'] = paddings
            nn_op_name = name_generator("pad2d", self.nn_name2id)
        else:
            layer_attrs['paddings'] = paddings
        if op_independent:
            self.paddle_graph.add_layer(
                paddle_op, 
S
SunAhong1993 已提交
429 430
                inputs={'x': val_x.name}, 
                outputs=[nn_op_name, node.name] if paddle_op == 'paddle.nn.Pad2D' else [node.name], 
S
SunAhong1993 已提交
431 432 433 434
                **layer_attrs)
        else:
            self.paddle_graph.add_layer(
                paddle_op,
S
SunAhong1993 已提交
435 436 437
                inputs={'x': val_x.name},
                outputs=[nn_op_name, node.name + '_paded'] if paddle_op == 'paddle.nn.Pad2D' \
                    else [node.name + '_paded'],
S
SunAhong1993 已提交
438
                **layer_attrs)
S
SunAhong1993 已提交
439
            return node.name + '_paded'
S
SunAhong1993 已提交
440 441 442 443 444 445 446

    @print_mapping_info
    def Unsqueeze(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        axes = node.get_attr('axes')
        layer_attrs = {'axis': axes}
        if len(val_x.out_shapes[0]) == 0:
S
SunAhong1993 已提交
447
            if node.name:
S
SunAhong1993 已提交
448 449
                self.paddle_graph.add_layer(
                    'paddle.reshape',
S
SunAhong1993 已提交
450 451
                    inputs={"x": val_x.name},
                    outputs=[node.name],
S
SunAhong1993 已提交
452 453
                    shape=[1])
        else:
S
fix  
SunAhong1993 已提交
454 455
            self.paddle_graph.add_layer(
                'paddle.unsqueeze', 
S
SunAhong1993 已提交
456 457
                inputs={"x": val_x.name}, 
                outputs=[node.name],
S
fix  
SunAhong1993 已提交
458
                **layer_attrs)
S
SunAhong1993 已提交
459 460 461 462 463 464 465 466 467

    @print_mapping_info
    def Shrink(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        bias = node.get_attr('bias')
        lambd = node.get_attr('lambd')
        assert bias == 0.0, 'not support bias!=0'
        self.paddle_graph.add_layer(
            'paddle.nn.functional.hardshrink', 
S
SunAhong1993 已提交
468 469
            inputs={"x": val_x.name}, 
            outputs=[node.name], 
S
SunAhong1993 已提交
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
            threshold=lambd)

    @print_mapping_info
    def Constant(self, node):
        val_output = self.graph.get_node(node.layer.output[0], copy=True)

        value = node.get_attr('value')
        dtype = np.dtype(value.dtype)
        output_dtype = val_output.dtype
        if output_dtype:
            assert dtype == output_dtype, 'tensor dtype unmatches storage dtype'

        shape = node.get_attr('shape', None)

        if shape is None:
            shape = val_output.out_shapes[0]
        if shape is None:
            shape = list(value.shape)
            _logger.warning('in (Constant -> %s): '
                            'attribute "shape" of %s not inferred, '
                            'using value as 1-D tensor may lead to fails',
S
SunAhong1993 已提交
491
                            val_output.name, val_output.name)
S
SunAhong1993 已提交
492 493 494 495 496 497
        if len(value) == 1:
            value = value.tolist()
            value = value[0]
            self.paddle_graph.add_layer(
                "paddle.full", 
                inputs={}, 
S
SunAhong1993 已提交
498
                outputs=[node.name],
S
SunAhong1993 已提交
499 500 501 502 503
                dtype=string(dtype),
                shape=[1],
                fill_value=value)
        else:
            value = np.reshape(value, shape)
S
SunAhong1993 已提交
504
            self.weights[node.name] = value
S
SunAhong1993 已提交
505 506 507
            self.paddle_graph.add_layer(
                "self.create_parameter",
                inputs={},
S
SunAhong1993 已提交
508
                outputs=[node.name],
S
SunAhong1993 已提交
509
                shape=shape,
S
SunAhong1993 已提交
510
                attr=string(node.name),
S
SunAhong1993 已提交
511 512 513 514 515 516 517 518 519 520 521 522 523 524
                dtype=string(dtype),
                default_initializer="paddle.nn.initializer.Constant(value=0.0)")

    @print_mapping_info
    def Resize(self, node):
        self._interpolate(node)

    @print_mapping_info
    def Upsample(self, node):
        self._interpolate(node)

    @print_mapping_info
    def InstanceNormalization(self, node):
        op_name = name_generator("instanse_norm", self.nn_name2id)
S
SunAhong1993 已提交
525
        output_name = node.name
S
SunAhong1993 已提交
526 527 528 529 530 531 532 533
        layer_outputs = [op_name, output_name]
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_scale = self.graph.get_input_node(node, idx=1, copy=True)
        val_b = self.graph.get_input_node(node, idx=2, copy=True)
        epsilon = node.get_attr('epsilon', 1e-5)
        layer_attrs = {
            'num_features': node.out_shapes[0][1],
            'epsilon': epsilon,
S
SunAhong1993 已提交
534 535
            'weight_attr': string(val_scale.name),
            'bias_attr': string(val_b.name)
S
SunAhong1993 已提交
536 537
        }
        dim = len(val_x.out_shapes[0])
S
SunAhong1993 已提交
538
        if dim == 3:
S
SunAhong1993 已提交
539 540 541 542 543 544 545 546 547
            paddle_op = "paddle.nn.InstanceNorm1D"
        elif dim == 4:
            paddle_op = "paddle.nn.InstanceNorm2D"
        elif dim == 5:
            paddle_op = "paddle.nn.InstanceNorm3D"
        else:
            raise Exception("The paddle only support 2D, 3D, 4D or 5D input in InstanceNormalization.")
        self.paddle_graph.add_layer(
            paddle_op, 
S
SunAhong1993 已提交
548
            inputs={"x": val_x.name}, 
S
SunAhong1993 已提交
549 550 551 552 553 554 555 556
            outputs=layer_outputs, 
            **layer_attrs)

    @print_mapping_info
    def Expand(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_shape = self.graph.get_input_node(node, idx=1, copy=True)
        val_x_dtype = val_x.dtype
S
SunAhong1993 已提交
557
        name_ones = node.name + '_ones'
S
SunAhong1993 已提交
558
        attr_ones = {
S
SunAhong1993 已提交
559
            'shape': val_shape.name,
S
SunAhong1993 已提交
560 561 562 563 564 565 566 567 568
            'dtype': string(val_x_dtype),
            'fill_value': 1
        }
        self.paddle_graph.add_layer(
            'paddle.full',
            inputs={},
            outputs=[name_ones],
            **attr_ones)
        inputs_dict = {'x': name_ones, 
S
SunAhong1993 已提交
569
                       'y': val_x.name}
S
SunAhong1993 已提交
570 571 572
        self.paddle_graph.add_layer(
            'paddle.multiply',
            inputs=inputs_dict,
S
SunAhong1993 已提交
573
            outputs=[node.name])
S
SunAhong1993 已提交
574 575 576 577 578 579 580 581 582 583 584 585 586

    @print_mapping_info
    def Gather(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        indices = self.graph.get_input_node(node, idx=1, copy=True)
        indices_shape = indices.out_shapes[0]
        axis = node.get_attr('axis', 0)
        #assert len(
        #    indices_shape) <= 2, "Gather op don't support dim of indice >2 "
        if axis == 0 and len(indices_shape) <= 1:
            if len(val_x.out_shapes[0]) <= 1:
                self.paddle_graph.add_layer(
                    'paddle.gather',
S
SunAhong1993 已提交
587 588 589
                    inputs={'x': val_x.name,
                            'index': indices.name},
                    outputs=[node.name])
S
SunAhong1993 已提交
590 591
            elif len(val_x.out_shapes[0]) > 1:
                if len(indices_shape) == 0:
S
SunAhong1993 已提交
592
                    gather_ = node.name + '_1'
S
SunAhong1993 已提交
593 594
                    self.paddle_graph.add_layer(
                        'paddle.gather',
S
SunAhong1993 已提交
595 596
                        inputs={'x': val_x.name,
                                'index': indices.name},
S
SunAhong1993 已提交
597 598 599 600
                        outputs=[gather_])
                    self.paddle_graph.add_layer(
                        'paddle.squeeze',
                        inputs={'x': gather_},
S
SunAhong1993 已提交
601
                        outputs=[node.name],
S
SunAhong1993 已提交
602 603 604 605
                        axis=[0])
                else:
                    self.paddle_graph.add_layer(
                        'paddle.gather',
S
SunAhong1993 已提交
606 607 608
                        inputs={'x': val_x.name,
                                'index': indices.name},
                        outputs=[node.name])
S
SunAhong1993 已提交
609 610 611
        elif axis > 0 and len(indices_shape) <= 1:
            perm = list(range(len(val_x.out_shapes[0])))
            perm = [axis] + perm[:axis] + perm[axis + 1:]
S
SunAhong1993 已提交
612
            name_trans = val_x.name + '_trans'
S
SunAhong1993 已提交
613 614
            self.paddle_graph.add_layer(
                'paddle.transpose',
S
SunAhong1993 已提交
615
                inputs={"x": val_x.name},
S
SunAhong1993 已提交
616 617 618 619 620
                outputs=[name_trans],
                perm=perm)
            self.paddle_graph.add_layer(
                'paddle.gather',
                inputs={'x': name_trans,
S
SunAhong1993 已提交
621 622
                        'index': indices.name},
                outputs=[node.name])
S
SunAhong1993 已提交
623 624
            self.paddle_graph.add_layer(
                'paddle.transpose', 
S
SunAhong1993 已提交
625 626
                inputs={"x": node.name}, 
                outputs=[node.name], 
S
SunAhong1993 已提交
627 628 629 630
                perm=perm)
            if len(indices_shape) < 1:
                self.paddle_graph.add_layer(
                    'paddle.squeeze',
S
SunAhong1993 已提交
631 632
                    inputs={'x': node.name},
                    outputs=[node.name],
S
SunAhong1993 已提交
633 634 635 636
                    axis=[axis])
        elif axis == 0 and len(indices_shape) > 1:
            if val_x.out_shapes[0] is not None and isinstance(
                    val_x, ONNXGraphDataNode):
S
SunAhong1993 已提交
637
                indices_cast = indices.name + '_cast'
S
SunAhong1993 已提交
638 639
                self.paddle_graph.add_layer(
                    'paddle.cast',
S
SunAhong1993 已提交
640
                    inputs={"x": indices.name},
S
SunAhong1993 已提交
641 642 643
                    outputs=indices_cast,
                    dtype=string('int64'))
                op_name = name_generator("embedding", self.nn_name2id)
S
SunAhong1993 已提交
644
                output_name = node.name
S
SunAhong1993 已提交
645 646 647 648 649
                layer_outputs = [op_name, output_name]
                self.paddle_graph.add_layer(
                    'paddle.nn.Embedding',
                    inputs={"x": indices_cast},
                    outputs=layer_outputs,
S
SunAhong1993 已提交
650
                    param_attr=string(val_x.name),
S
SunAhong1993 已提交
651 652 653 654
                    size=val_x.out_shapes[0])
            else:
                from functools import reduce
                reshape_shape = reduce(lambda x, y: x * y, indices_shape)
S
SunAhong1993 已提交
655
                indices_reshape = indices.name + '_shape'
S
SunAhong1993 已提交
656 657
                self.paddle_graph.add_layer(
                    'paddle.reshape',
S
SunAhong1993 已提交
658
                    inputs={"x": indices.name},
S
SunAhong1993 已提交
659 660 661 662 663 664
                    outputs=[indices_reshape],
                    shape=[reshape_shape, ])

                perm = list(range(len(val_x.out_shapes[0])))
                self.paddle_graph.add_layer(
                    'paddle.gather',
S
SunAhong1993 已提交
665
                    inputs={'x': val_x.name,
S
SunAhong1993 已提交
666
                            'index': indices_reshape},
S
SunAhong1993 已提交
667
                    outputs=[node.name])
S
SunAhong1993 已提交
668 669 670 671 672 673 674 675
                val_x_shape = val_x.out_shapes[0]
                reshaped_shape = []
                for i in perm:
                    reshaped_shape.append(indices_shape[i])
                for i in val_x_shape[:axis] + val_x_shape[axis + 1:]:
                    reshaped_shape.append(i)
                self.paddle_graph.add_layer(
                    'paddle.reshape',
S
SunAhong1993 已提交
676 677
                    inputs={"x": node.name},
                    outputs=[node.name],
S
SunAhong1993 已提交
678 679 680 681
                    shape=reshaped_shape)
        elif axis > 0 and len(indices_shape) > 1:
            from functools import reduce
            reshape_shape = reduce(lambda x, y: x * y, indices_shape)
S
SunAhong1993 已提交
682
            indices_reshape = indices.name + '_shape'
S
SunAhong1993 已提交
683 684
            self.paddle_graph.add_layer(
                'paddle.reshape',
S
SunAhong1993 已提交
685
                inputs={"x": indices.name},
S
SunAhong1993 已提交
686 687 688 689 690
                outputs=[indices_reshape],
                shape=[reshape_shape, ])

            perm = list(range(len(val_x.out_shapes[0])))
            perm = [axis] + perm[:axis] + perm[axis + 1:]
S
SunAhong1993 已提交
691
            name_trans = val_x.name + '_transpose'
S
SunAhong1993 已提交
692 693
            self.paddle_graph.add_layer(
                'paddle.transpose',
S
SunAhong1993 已提交
694
                inputs={"x": val_x.name},
S
SunAhong1993 已提交
695 696 697 698 699 700
                outputs=[name_trans],
                perm=perm)
            self.paddle_graph.add_layer(
                'paddle.gather',
                inputs={'x': name_trans,
                        'index': indices_reshape},
S
SunAhong1993 已提交
701 702
                outputs=[node.name])
            input_transpose = node.name + '_transpose'
S
SunAhong1993 已提交
703 704
            self.paddle_graph.add_layer(
                'paddle.transpose',
S
SunAhong1993 已提交
705
                inputs={"x": node.name},
S
SunAhong1993 已提交
706 707 708 709 710 711 712 713 714 715 716
                outputs=[input_transpose],
                perm=perm)
            val_x_shape = val_x.out_shapes[0]
            reshaped_shape = []
            for i in perm:
                reshaped_shape.append(indices_shape[i])
            for i in val_x_shape[:axis] + val_x_shape[axis + 1:]:
                reshaped_shape.append(i)
            self.paddle_graph.add_layer(
                'paddle.reshape',
                inputs={"x": input_transpose},
S
SunAhong1993 已提交
717
                outputs=[node.name],
S
SunAhong1993 已提交
718 719 720 721 722 723 724 725 726 727
                shape=reshaped_shape)

    @print_mapping_info
    def ScatterND(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        indices = self.graph.get_input_node(node, idx=1, copy=True)
        updates = self.graph.get_input_node(node, idx=2, copy=True)
        if len(indices.out_shapes[0]) == 1:
            self.paddle_graph.add_layer(
                'paddle.scatter',
S
SunAhong1993 已提交
728 729 730 731
                inputs={'x': val_x.name,
                        'index': indices.name,
                        'updates': updates.name},
                outputs=[node.name])
S
SunAhong1993 已提交
732
        else:
S
SunAhong1993 已提交
733
            input_inner_indices = node.name + '_input_inner_indices'
S
SunAhong1993 已提交
734 735 736
            shape = val_x.out_shapes[0]
            self.paddle_graph.add_layer(
                'paddle.reshape',
S
SunAhong1993 已提交
737 738
                inputs={"x": indices.name},
                outputs=[indices.name],
S
SunAhong1993 已提交
739 740
                shape=indices.out_shapes[0])

S
SunAhong1993 已提交
741
            zeros_like_val_x = val_x.name + '_zeros'
S
SunAhong1993 已提交
742 743
            self.paddle_graph.add_layer(
                'paddle.zeros_like',
S
SunAhong1993 已提交
744
                inputs={"x": val_x.name},
S
SunAhong1993 已提交
745 746 747 748 749
                outputs=[zeros_like_val_x])
            self.paddle_graph.add_layer(
                'paddle.scatter_nd_add',
                inputs={
                    'x': zeros_like_val_x,
S
SunAhong1993 已提交
750 751
                    'index': indices.name,
                    'updates': updates.name
S
SunAhong1993 已提交
752 753
                },
                outputs=[input_inner_indices])
S
SunAhong1993 已提交
754 755
            indices_mask = node.name + '_indices_mask'
            constant_minus_one = node.name + '_constant_minus_one'
S
SunAhong1993 已提交
756 757 758
            # full_like support create tensor shape like input tensor
            self.paddle_graph.add_layer(
                'paddle.full_like',
S
SunAhong1993 已提交
759
                inputs={"x": updates.name},
S
SunAhong1993 已提交
760 761 762 763 764 765 766
                outputs=[constant_minus_one],
                dtype=string(updates.dtype),
                fill_value=-1)
            self.paddle_graph.add_layer(
                'paddle.scatter_nd_add',
                inputs={
                    'x': zeros_like_val_x,
S
SunAhong1993 已提交
767
                    'index': indices.name,
S
SunAhong1993 已提交
768 769 770
                    'updates': constant_minus_one
                },
                outputs=[indices_mask])
S
SunAhong1993 已提交
771
            constant_one = node.name + '_constant_1'
S
SunAhong1993 已提交
772 773 774
            # full_like support create tensor shape like input tensor
            self.paddle_graph.add_layer(
                'paddle.full_like',
S
SunAhong1993 已提交
775
                inputs={"x": val_x.name},
S
SunAhong1993 已提交
776 777 778
                outputs=[constant_one],
                dtype=string(val_x.dtype),
                fill_value=1)
S
SunAhong1993 已提交
779
            input_out_indices_mask = node.name + '_input_out_indices_mask'
S
SunAhong1993 已提交
780 781 782 783 784 785
            self.paddle_graph.add_layer(
                "paddle.add",
                inputs={"x": indices_mask,
                        "y": constant_one},
                outputs=[input_out_indices_mask])

S
SunAhong1993 已提交
786
            input_out_indices = node.name + '_input_out_indices'
S
SunAhong1993 已提交
787 788
            self.paddle_graph.add_layer(
                "paddle.multiply",
S
SunAhong1993 已提交
789
                inputs={"x": val_x.name,
S
SunAhong1993 已提交
790 791 792 793 794 795 796
                        "y": input_out_indices_mask},
                outputs=[input_out_indices])

            self.paddle_graph.add_layer(
                "paddle.add",
                inputs={"x": input_inner_indices,
                        "y": input_out_indices},
S
SunAhong1993 已提交
797
                outputs=[node.name])
S
SunAhong1993 已提交
798 799 800 801 802 803 804

    @print_mapping_info
    def Range(self, node):
        val_start = self.graph.get_input_node(node, idx=0, copy=True)
        val_limit = self.graph.get_input_node(node, idx=1, copy=True)
        val_delta = self.graph.get_input_node(node, idx=2, copy=True)
        dtype = val_start.dtype
S
SunAhong1993 已提交
805 806 807
        inputs = {'start': val_start.name, 
                  'end': val_limit.name, 
                  'step': val_delta.name}
S
SunAhong1993 已提交
808 809 810
        self.paddle_graph.add_layer(
            'paddle.arange',
            inputs=inputs,
S
SunAhong1993 已提交
811
            outputs=[node.name],
S
SunAhong1993 已提交
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
            dtype=string(dtype))

    @print_mapping_info
    def Slice(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        starts, ends, axes, steps = None, None, None, None
        layer_attrs = {}
        if len(node.inputs) > 1:
            starts = self.graph.get_input_node(node, idx=1, copy=True)
            ends = self.graph.get_input_node(node, idx=2, copy=True)
            starts_value = _const_weight_or_none(starts)
            ends_value = _const_weight_or_none(ends)

            if len(node.inputs) > 3:
                axes = self.graph.get_input_node(node, idx=3, copy=True)
                axes = _const_weight_or_none(axes, necessary=True)
            if len(node.inputs) > 4:
                steps = self.graph.get_input_node(node, idx=4, copy=True)
                steps = _const_weight_or_none(steps)
            layer_attrs = {
                "axes": axes,
S
SunAhong1993 已提交
833 834
                "starts": starts.name,
                "ends": ends.name
S
SunAhong1993 已提交
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
            }
            if starts_value is not None and ends_value is not None:
                starts_value = starts_value.copy()
                ends_value = ends_value.copy()
                #for idx in range(len(ends_value)):
                #    if ends_value[idx] > 2**31 - 1:
                #        ends_value[idx] = 2**31 - 1
                #print(val_x.out_shapes)
                for idx in range(len(ends_value)):
                    if starts_value[idx] >= val_x.out_shapes[0][axes[idx]]:
                        starts_value[idx] = val_x.out_shapes[0][axes[idx]] - 1
                        ends_value[idx] = val_x.out_shapes[0][axes[idx]]
                        starts_value[idx] = val_x.out_shapes[0][axes[idx]] - 1
                    elif ends_value[idx] > 2**31 - 1:
                        ends_value[idx] = 2**31 - 1
                layer_attrs = {
                    "axes": axes,
                    "starts": starts_value,
                    "ends": ends_value
                }
            else:
                if starts.dtype != 'int32':
S
SunAhong1993 已提交
857
                    starts_cast = starts.name + '_cast'
S
SunAhong1993 已提交
858 859
                    self.paddle_graph.add_layer(
                        'paddle.cast',
S
SunAhong1993 已提交
860
                        inputs={"x": starts.name},
S
SunAhong1993 已提交
861 862 863 864
                        outputs=[starts_cast],
                        dtype=string('int32'))
                    layer_attrs['starts'] = starts_cast
                if ends.dtype != 'int32':
S
SunAhong1993 已提交
865
                    ends_cast = ends.name + '_cast'
S
SunAhong1993 已提交
866 867
                self.paddle_graph.add_layer(
                    'paddle.cast',
S
SunAhong1993 已提交
868
                    inputs={"x": ends.name},
S
SunAhong1993 已提交
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
                    outputs=[ends_cast],
                    dtype=string('int32'))
                layer_attrs['ends'] = ends_cast
        else:
            starts = node.get_attr('starts')
            ends = node.get_attr('ends')
            axes = node.get_attr('axes')
            for idx in range(len(ends)):
                if ends[idx] > 2**31 - 1:
                    ends[idx] = 2**31 - 1
            layer_attrs = {"axes": axes, "starts": starts, "ends": ends}

        if steps is not None:
            layer_attrs['strides'] = steps
            self.paddle_graph.add_layer(
                'paddle.strided_slice', 
S
SunAhong1993 已提交
885 886
                inputs={"x": val_x.name}, 
                outputs=[node.name], 
S
SunAhong1993 已提交
887 888 889 890
                **layer_attrs)
        else:
            self.paddle_graph.add_layer(
                'paddle.slice', 
S
SunAhong1993 已提交
891 892
                inputs={"input": val_x.name}, 
                outputs=[node.name],  
S
SunAhong1993 已提交
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
                **layer_attrs)

    @print_mapping_info
    def ConstantOfShape(self, node):
        val_shape = self.graph.get_input_node(node, idx=0, copy=True)
        val_y = self.graph.get_node(node.layer.output[0], copy=True)

        value = node.get_attr('value')
        dtype = value.dtype
        value = value.tolist()
        assert len(value) == 1, ('given value not Scalar, shape of value > 1, '
                                 'this is not supported')
        if len(value) == 1:
            value = value[0]
            layer_attrs = {
S
SunAhong1993 已提交
908
                'shape': val_shape.name,
S
SunAhong1993 已提交
909 910 911 912 913 914
                'dtype': string(dtype),
                'fill_value': value
            }
            self.paddle_graph.add_layer(
                "paddle.full", 
                inputs={}, 
S
SunAhong1993 已提交
915
                outputs=[node.name],
S
SunAhong1993 已提交
916 917 918 919 920 921 922 923 924 925 926 927 928 929
                **layer_attrs)

    @print_mapping_info
    def Clip(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_y = self.graph.get_node(node.layer.output[0], copy=True)
        max_value, min_value = None, None
        if len(node.inputs) == 1:
            max_value = node.get_attr('max')
            min_value = node.get_attr('min')
            layer_attrs = {
                'max': max_value,
                'min': min_value,
            }
S
SunAhong1993 已提交
930
            
S
SunAhong1993 已提交
931 932
            self.paddle_graph.add_layer(
                'paddle.clip', 
S
SunAhong1993 已提交
933 934
                inputs={"x": val_x.name}, 
                outputs=[node.name], 
S
SunAhong1993 已提交
935 936
                **layer_attrs)
        else:
S
SunAhong1993 已提交
937 938
            min_ipt = self.graph.get_input_node(node, idx=1, copy=True)
            max_ipt = self.graph.get_input_node(node, idx=2, copy=True)
S
SunAhong1993 已提交
939
            min_value = _const_weight_or_none(min_ipt)
S
SunAhong1993 已提交
940
            max_value = _const_weight_or_none(max_ipt)
S
SunAhong1993 已提交
941 942 943 944 945 946 947 948
            if max_value.shape == (1, ):
                max_value = max_value[0]
            if min_value.shape == (1, ):
                min_value = min_value[0]
        if max_value is not None and min_value is not None:
            layer_attrs = {'max': max_value, 'min': min_value}
            self.paddle_graph.add_layer(
                'paddle.clip', 
S
SunAhong1993 已提交
949 950
                inputs={"x": val_x.name}, 
                outputs=[node.name], 
S
SunAhong1993 已提交
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
                **layer_attrs)
        else:
            raise

    @print_mapping_info
    def Split(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        paddle_op = 'split'
        split = node.get_attr('split')
        axis = node.get_attr('axis', 0)
        layer_attrs = {
            'num_or_sections': split,
            'axis': axis,
        }
        outputs_list = list()
        if isinstance(split, list) or isinstance(split, tuple):
S
fix  
SunAhong1993 已提交
967 968
            for i in range(len(split)):
                outputs_list.append("{}_p{}".format(node.layer_name, i))
S
SunAhong1993 已提交
969
        else:
S
SunAhong1993 已提交
970
            outputs_list.append(node.name)
S
SunAhong1993 已提交
971 972
        self.paddle_graph.add_layer(
            'paddle.split', 
S
SunAhong1993 已提交
973
            inputs={"x": val_x.name}, 
S
SunAhong1993 已提交
974 975 976 977 978 979 980 981 982 983 984 985 986 987
            outputs=outputs_list, 
            **layer_attrs)

    @print_mapping_info
    def Reshape(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_shape = self.graph.get_input_node(node, idx=1, copy=True)
        val_reshaped = self.graph.get_node(node.layer.output[0], copy=True)
        shape_value = _const_weight_or_none(val_shape)
        shape_dims = len(val_shape.out_shapes[0])

        if shape_value is not None:
            self.paddle_graph.add_layer(
                'paddle.reshape',
S
SunAhong1993 已提交
988 989
                inputs={'x': val_x.name},
                outputs=[node.name],
S
SunAhong1993 已提交
990 991 992 993 994
                shape=shape_value.tolist())
        elif len(node.out_shapes[0]) > 0 and _is_static_shape(node.out_shapes[
                0]):
            self.paddle_graph.add_layer(
                'paddle.reshape',
S
SunAhong1993 已提交
995 996
                inputs={'x': val_x.name},
                outputs=[node.name],
S
SunAhong1993 已提交
997 998 999 1000 1001 1002
                shape=node.out_shapes[0])
        else:
            # shape may be [], come form Gather by scalar indices
            if len(val_shape.out_shapes[0]) > 0:
                self.paddle_graph.add_layer(
                    'paddle.reshape',
S
SunAhong1993 已提交
1003 1004
                    inputs={'x': val_shape.name},
                    outputs=[val_shape.name],
S
SunAhong1993 已提交
1005 1006 1007
                    shape=val_shape.out_shapes[0])
            self.paddle_graph.add_layer(
                'paddle.reshape',
S
SunAhong1993 已提交
1008 1009
                inputs={'x': val_x.name,
                        'shape': val_shape.name},
S
SunAhong1993 已提交
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
                outputs=node)

    @print_mapping_info
    def Cast(self, node):
        val_input = self.graph.get_input_node(node, idx=0, copy=True)
        val_output = self.graph.get_node(node.layer.output[0], copy=True)

        dtype = node.get_attr('to')
        if not isinstance(dtype, np.dtype):
            dtype = TENSOR_TYPE_TO_NP_TYPE[dtype]

        output_dtype = val_output.dtype
        if output_dtype:
            assert dtype == output_dtype, 'dtype of to unmatches output'
        self.paddle_graph.add_layer(
            'paddle.cast', 
S
SunAhong1993 已提交
1026 1027
            inputs={'x': val_input.name}, 
            outputs=[node.name], 
S
SunAhong1993 已提交
1028 1029 1030 1031 1032 1033
            dtype=string(dtype))

    @print_mapping_info
    def Not(self, node):
        val_input = self.graph.get_input_node(node, idx=0, copy=True)
        self.paddle_graph.add_layer('paddle.logical_not', 
S
SunAhong1993 已提交
1034 1035
                                    inputs={'x': val_input.name}, 
                                    outputs=[node.name])
S
SunAhong1993 已提交
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067

    @print_mapping_info
    def AveragePool(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)

        auto_pad = node.get_attr('auto_pad', 'NOTSET')
        kernel_shape = node.get_attr("kernel_shape")
        poolnd = len(kernel_shape)
        strides = node.get_attr("strides")
        pad_mode = node.get_attr("pads")
        ceil_mode = bool(node.get_attr('ceil_mode', 0))
        pads = node.get_attr('pads', [0] * (poolnd * 2))

        paddings, val_x = self._pad_if_asymmetric(node, pads, val_x)

        if auto_pad == "SAME_UPPER" or auto_pad == "SAME_LOWER":
            input_shape = val_x.out_shapes[0]
            pad_h = _get_same_padding(input_shape[2], kernel_shape[0],
                                      strides[0])
            pad_w = _get_same_padding(input_shape[3], kernel_shape[1],
                                      strides[1])
            paddings = pad_h + pad_w

        paddle_op = 'fluid.layers.pool{}d'.format(poolnd)
        assert 2 <= poolnd <= 3, 'only pool2d and pool3d are supported'
        layer_attrs = {
            "pool_size": kernel_shape,
            "pool_type": string('avg'),
            "pool_stride": strides,
            "pool_padding": paddings,
            "ceil_mode": ceil_mode,
            "exclusive": 'True',
S
SunAhong1993 已提交
1068
            "name": string(node.name)
S
SunAhong1993 已提交
1069 1070 1071
        }
        self.paddle_graph.add_layer(
            paddle_op, 
S
SunAhong1993 已提交
1072 1073
            inputs={'input': val_x if isinstance(val_x, str) else val_x.name}, 
            outputs=[node.name], 
S
SunAhong1993 已提交
1074 1075 1076
            **layer_attrs)
        # TODO(syf): op has diff
#         op_name = name_generator("pool", self.nn_name2id)
S
SunAhong1993 已提交
1077
#         output_name = node.name
S
SunAhong1993 已提交
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
#         layer_outputs = [op_name, output_name]
#         paddle_op = 'paddle.nn.Pool{}D'.format(poolnd)
#         assert 1 <= poolnd <= 3, 'only Pool1D, Pool2D and Pool3D are supported'
#         layer_attrs = {
#             "kernel_size": kernel_shape,
#             "stride": strides,
#             "padding": paddings,
#             "ceil_mode": ceil_mode,
#             "exclusive": 'True',
#         }
#         self.paddle_graph.add_layer(
#             paddle_op, 
S
SunAhong1993 已提交
1090
#             inputs={'x': val_x.name}, 
S
SunAhong1993 已提交
1091 1092 1093 1094 1095 1096 1097 1098 1099
#             outputs=layer_outputs, 
#             **layer_attrs)

    @print_mapping_info
    def Concat(self, node):
        inputs_list = []
        dtypes = set()
        for i in range(len(node.layer.input)):
            ipt = self.graph.get_input_node(node, idx=i, copy=True)
S
SunAhong1993 已提交
1100 1101 1102 1103
            try:
                print(ipt.index)
            except:
                pass
S
SunAhong1993 已提交
1104
            inputs_list.append(ipt.name)
S
SunAhong1993 已提交
1105 1106 1107 1108 1109 1110 1111
            dtypes.add(ipt.dtype)
        if len(dtypes) > 1:
            assert 'Unspported situation happened, please create issue on https://github.com/PaddlePaddle/X2Paddle/issues.'
        axis = node.get_attr('axis')
        self.paddle_graph.add_layer(
            'paddle.concat', 
            inputs={"x": inputs_list}, 
S
SunAhong1993 已提交
1112
            outputs=[node.name], 
S
SunAhong1993 已提交
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
            axis=axis)

    @print_mapping_info
    def Flatten(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        output_shape = node.out_shapes[0]
        axis = node.get_attr('axis', 1)
        shape_list = [1, 1]
        if axis == 0:
            for s in output_shape:
                shape_list[1] *= s
        else:
            for s in output_shape[:axis]:
                shape_list[0] *= s
            for s in output_shape[axis:]:
                shape_list[1] *= s
        self.paddle_graph.add_layer(
            'paddle.reshape', 
S
SunAhong1993 已提交
1131 1132
            inputs={"x": val_x.name}, 
            outputs=[node.name],
S
SunAhong1993 已提交
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
            shape=shape_list)

    @print_mapping_info
    def Gemm(self, node):
        val_a = self.graph.get_input_node(node, idx=0, copy=True)
        val_b = self.graph.get_input_node(node, idx=1, copy=True)
        val_c = self.graph.get_input_node(node, idx=2, copy=True)

        alpha = node.get_attr('alpha', 1.)  # optional
        beta = node.get_attr('beta', 1.)  # optional
        trans_a = bool(node.get_attr('transA', 0))  # optional
        trans_b = bool(node.get_attr('transB', 0))  # optional
S
SunAhong1993 已提交
1145 1146 1147
        val_mm = node.name + '_mm'
        matmul_inputs = {"x": val_a.name, 
                         "y": val_b.name}
S
SunAhong1993 已提交
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
        attr_matmul = {
            "transpose_x": trans_a,
            "transpose_y": trans_b,
        }
        self.paddle_graph.add_layer(
            'paddle.matmul',
            inputs=matmul_inputs,
            outputs=[val_mm],
            **attr_matmul)
        self.paddle_graph.add_layer(
            "paddle.scale", 
            inputs={"x": val_mm}, 
            outputs=[val_mm],
            scale=alpha)

        if beta != 0:
            if beta == 1.:
                add_inputs = {"x": val_mm, 
S
SunAhong1993 已提交
1166
                              "y": val_c.name}
S
SunAhong1993 已提交
1167 1168 1169
                self.paddle_graph.add_layer(
                    "paddle.add",
                    inputs=add_inputs,
S
SunAhong1993 已提交
1170
                    outputs=[node.name])
S
SunAhong1993 已提交
1171
            else:
S
SunAhong1993 已提交
1172
                var_beta = node.name + '_beta'
S
SunAhong1993 已提交
1173 1174
                self.paddle_graph.add_layer(
                    "paddle.scale",
S
SunAhong1993 已提交
1175
                    inputs={"x": val_c.name},
S
SunAhong1993 已提交
1176 1177 1178 1179
                    outputs=[var_beta],
                    scale=beta)
                add_inputs = {"x": val_mm, "y": var_beta}
                self.paddle_graph.add_layer(
S
SunAhong1993 已提交
1180
                    "paddle.add",
S
SunAhong1993 已提交
1181
                    inputs=add_inputs,
S
SunAhong1993 已提交
1182
                    outputs=[node.name])
S
SunAhong1993 已提交
1183 1184 1185 1186 1187

    @print_mapping_info
    def Sum(self, node):
        val_inps = node.layer.input
        inputs_dict = {
S
SunAhong1993 已提交
1188 1189 1190 1191
            "x": self.graph.get_input_node(
                node, idx=0, copy=True).name,
            "y": self.graph.get_input_node(
                node, idx=1, copy=True).name,
S
SunAhong1993 已提交
1192 1193 1194
        }
        self.paddle_graph.add_layer("paddle.add", 
                                    inputs=inputs_dict, 
S
SunAhong1993 已提交
1195
                                    outputs=[node.name])
S
SunAhong1993 已提交
1196 1197 1198 1199

        for idx, ipt in enumerate(val_inps[2:]):
            y = self.graph.get_input_node(node, idx=idx, copy=True)
            inputs_dict = {
S
SunAhong1993 已提交
1200 1201
                "x": node.name,
                "y": y.name,
S
SunAhong1993 已提交
1202 1203 1204 1205
            }
            self.paddle_graph.add_layer(
                "paddle.add", 
                inputs=inputs_dict, 
S
SunAhong1993 已提交
1206
                outputs=[node.name])
S
SunAhong1993 已提交
1207 1208 1209 1210 1211 1212 1213

    @print_mapping_info
    def MatMul(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_y = self.graph.get_input_node(node, idx=1, copy=True)
        x_shape = val_x.out_shapes[0]
        y_shape = val_y.out_shapes[0]
S
SunAhong1993 已提交
1214 1215
        inputs_dict = {"x": val_x.name, 
                       "y": val_y.name}
S
SunAhong1993 已提交
1216
        if y_shape[0] == 1 and x_shape[-1] != 1 and x_shape[0] != 1:
S
SunAhong1993 已提交
1217
            y_squeeze = val_y.name + '_squeeze'
S
SunAhong1993 已提交
1218 1219
            self.paddle_graph.add_layer(
                "paddle.squeeze",
S
SunAhong1993 已提交
1220
                inputs={"x": val_y.name},
S
SunAhong1993 已提交
1221 1222 1223 1224 1225 1226
                outputs=[y_squeeze],
                axis=[0])
            inputs_dict['y'] = y_squeeze
            self.paddle_graph.add_layer(
                "paddle.matmul", 
                inputs=inputs_dict, 
S
SunAhong1993 已提交
1227
                outputs=[node.name])
S
SunAhong1993 已提交
1228 1229 1230 1231
        else:
            self.paddle_graph.add_layer(
                "paddle.matmul", 
                inputs=inputs_dict, 
S
SunAhong1993 已提交
1232
                outputs=[node.name])
S
SunAhong1993 已提交
1233 1234 1235 1236

    @print_mapping_info
    def BatchNormalization(self, node):
        op_name = name_generator("batchnorm", self.nn_name2id)
S
SunAhong1993 已提交
1237
        output_name = node.name
S
SunAhong1993 已提交
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
        layer_outputs = [op_name, output_name]
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_scale = self.graph.get_input_node(node, idx=1, copy=True)
        val_b = self.graph.get_input_node(node, idx=2, copy=True)
        val_mean = self.graph.get_input_node(node, idx=3, copy=True)
        val_var = self.graph.get_input_node(node, idx=4, copy=True)

        momentum = node.get_attr('momentum', .9)
        epsilon = node.get_attr('epsilon', 1e-5)
        c = val_x.out_shapes[0][1]

        # Attribute: spatial is used in BatchNormalization-1,6,7
        spatial = bool(node.get_attr('spatial'))
        layer_attrs = {
            "num_channels": c,
            "momentum": momentum,
            "epsilon": epsilon,
            "is_test": True,
S
SunAhong1993 已提交
1256 1257 1258 1259
            "param_attr": string(val_scale.name),
            "bias_attr": string(val_b.name),
            "moving_mean_name": string(val_mean.name),
            "moving_variance_name": string(val_var.name),
S
SunAhong1993 已提交
1260 1261 1262 1263
            "use_global_stats": False,
        }
        self.paddle_graph.add_layer(
            "paddle.nn.BatchNorm", 
S
SunAhong1993 已提交
1264
            inputs={"x": val_x.name}, 
S
SunAhong1993 已提交
1265 1266 1267 1268 1269 1270 1271 1272 1273
            outputs=layer_outputs, 
            **layer_attrs)

    @print_mapping_info
    def Transpose(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        perm = node.get_attr('perm')
        self.paddle_graph.add_layer(
            "paddle.transpose", 
S
SunAhong1993 已提交
1274 1275
            inputs={"x": val_x.name},
            outputs=[node.name], 
S
SunAhong1993 已提交
1276 1277 1278 1279 1280
            perm=perm)

    @print_mapping_info
    def PRelu(self, node):
        op_name = name_generator("prelu", self.nn_name2id)
S
SunAhong1993 已提交
1281
        output_name = node.name
S
SunAhong1993 已提交
1282 1283 1284 1285 1286 1287 1288 1289 1290
        layer_outputs = [op_name, output_name]
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_slope = self.graph.get_input_node(node, idx=1, copy=True)

        mode = 'channel'
        shape_slope = val_slope.out_shapes[0]
        if shape_slope == [1]:
            mode = 'all'
        elif len(shape_slope) > 2:
S
SunAhong1993 已提交
1291
            raise Exception("The 'element' mode is not supported yet!")
S
SunAhong1993 已提交
1292 1293 1294 1295 1296

        if mode == 'channel' and len(shape_slope) == 1:
            # paddle params shape need be [1, channel]
            slope_data = _const_weight_or_none(val_slope)
            slope_data = np.reshape(slope_data, [1] + shape_slope)
S
SunAhong1993 已提交
1297
            self.weights[val_slope.name] = slope_data
S
SunAhong1993 已提交
1298 1299 1300
            num_parameters = val_x.out_shapes[0][1]
        else:
            num_parameters = 1
S
SunAhong1993 已提交
1301 1302 1303

        self.paddle_graph.add_layer(
            "paddle.nn.PReLU", 
S
SunAhong1993 已提交
1304
            inputs={"x": val_x.name}, 
S
SunAhong1993 已提交
1305
            outputs=layer_outputs, 
S
SunAhong1993 已提交
1306
            num_parameters=num_parameters,
S
SunAhong1993 已提交
1307
            weight_attr=string(val_slope.name))
S
SunAhong1993 已提交
1308 1309 1310 1311 1312 1313 1314 1315

    @print_mapping_info
    def Squeeze(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        axes = node.get_attr('axes')
        if len(val_x.out_shapes[0]) == 1:
            self.paddle_graph.add_layer(
                "paddle.cast",
S
SunAhong1993 已提交
1316 1317
                inputs={"x": val_x.name},
                outputs=[node.name],
S
SunAhong1993 已提交
1318 1319 1320 1321
                dtype=string(val_x.dtype))
        else:
            self.paddle_graph.add_layer(
                "paddle.squeeze", 
S
SunAhong1993 已提交
1322 1323
                inputs={"x": val_x.name}, 
                outputs=[node.name], 
S
SunAhong1993 已提交
1324 1325 1326 1327 1328 1329 1330 1331
                axis=axes)

    @print_mapping_info
    def Equal(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_y = self.graph.get_input_node(node, idx=1, copy=True)
        self.paddle_graph.add_layer(
            "paddle.equal",
S
SunAhong1993 已提交
1332 1333 1334
            inputs={'x': val_x.name,
                    'y': val_y.name},
            outputs=[node.name])
S
SunAhong1993 已提交
1335 1336 1337 1338 1339 1340 1341

    @print_mapping_info
    def Greater(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_y = self.graph.get_input_node(node, idx=1, copy=True)
        self.paddle_graph.add_layer(
            "paddle.greater_than",
S
SunAhong1993 已提交
1342 1343
            inputs={'x': val_x.name,
                    'y': val_y.name},
S
SunAhong1993 已提交
1344 1345 1346 1347 1348 1349 1350 1351 1352
            outputs=node,
            param_attr=None)

    @print_mapping_info
    def Where(self, node):
        condition = self.graph.get_input_node(node, idx=0, copy=True)
        val_x = self.graph.get_input_node(node, idx=1, copy=True)
        val_y = self.graph.get_input_node(node, idx=2, copy=True)

S
SunAhong1993 已提交
1353
        not_condition = condition.name + '_not'
S
SunAhong1993 已提交
1354 1355
        self.paddle_graph.add_layer(
            "paddle.logical_not",
S
SunAhong1993 已提交
1356
            inputs={"x": condition.name},
S
SunAhong1993 已提交
1357 1358 1359 1360 1361 1362 1363
            outputs=[not_condition])
        cast_not_condition = not_condition + '_cast'
        self.paddle_graph.add_layer(
            "paddle.cast",
            inputs={"x": not_condition},
            outputs=[cast_not_condition],
            dtype=string(val_x.dtype))
S
SunAhong1993 已提交
1364
        cast_condition = condition.name + '_cast'
S
SunAhong1993 已提交
1365 1366
        self.paddle_graph.add_layer(
            "paddle.cast",
S
SunAhong1993 已提交
1367
            inputs={"x": condition.name},
S
SunAhong1993 已提交
1368 1369
            outputs=[cast_condition],
            dtype=string(val_x.dtype))
S
SunAhong1993 已提交
1370
        mul_val_x = val_x.name + '_mul'
S
SunAhong1993 已提交
1371 1372
        self.paddle_graph.add_layer(
            "paddle.multiply",
S
SunAhong1993 已提交
1373
            inputs={'x': val_x.name,
S
SunAhong1993 已提交
1374 1375
                    'y': cast_condition},
            outputs=[mul_val_x])
S
SunAhong1993 已提交
1376
        mul_val_y = val_y.name + '_mul'
S
SunAhong1993 已提交
1377 1378
        self.paddle_graph.add_layer(
            "paddle.multiply",
S
SunAhong1993 已提交
1379
            inputs={'x': val_y.name,
S
SunAhong1993 已提交
1380 1381 1382 1383 1384 1385 1386
                    'y': cast_not_condition},
            outputs=[mul_val_y])

        self.paddle_graph.add_layer(
            "paddle.add",
            inputs={'x': mul_val_x,
                    'y': mul_val_y},
S
SunAhong1993 已提交
1387
            outputs=[node.name])
S
SunAhong1993 已提交
1388 1389 1390 1391 1392 1393 1394 1395

    @print_mapping_info
    def NonZero(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_x_dim = len(val_x.out_shapes[0])
        if val_x_dim == 1:
            self.paddle_graph.add_layer(
                "paddle.nonzero", 
S
SunAhong1993 已提交
1396 1397
                inputs={"x": val_x.name}, 
                outputs=[val_x.name])
S
SunAhong1993 已提交
1398 1399
            self.paddle_graph.add_layer(
                "paddle.transpose",
S
SunAhong1993 已提交
1400
                inputs={"x": val_x.name},
S
SunAhong1993 已提交
1401 1402 1403 1404 1405
                outputs=[node.layer_naem],
                perm=[1, 0])
        if val_x_dim > 1:
            self.paddle_graph.add_layer(
                "paddle.nonzero", 
S
SunAhong1993 已提交
1406 1407
                inputs={"x": val_x.name}, 
                outputs=[val_x.name])
S
SunAhong1993 已提交
1408 1409
            self.paddle_graph.add_layer(
                "paddle.split",
S
SunAhong1993 已提交
1410 1411
                inputs={"x": val_x.name}, 
                outputs=[val_x.name],
S
SunAhong1993 已提交
1412 1413 1414 1415
                num_or_sections=1,
                axis=val_x_dim)
            self.paddle_graph.add_layer(
                "paddle.concat", 
S
SunAhong1993 已提交
1416 1417
                inputs={"x": val_x.name}, 
                outputs=[node.name])
S
SunAhong1993 已提交
1418 1419 1420 1421 1422 1423

    @print_mapping_info
    def Identity(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        self.paddle_graph.add_layer(
            "paddle.assign", 
S
SunAhong1993 已提交
1424 1425
            inputs={"x": val_x.name}, 
            outputs=[node.name])
S
SunAhong1993 已提交
1426 1427 1428 1429 1430 1431 1432 1433

    @print_mapping_info
    def Tile(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_repeats = self.graph.get_input_node(node, idx=1, copy=True)
        repeats = _const_weight_or_none(val_repeats)

        if repeats is None:
S
SunAhong1993 已提交
1434
            repeats = val_repeats.name
S
SunAhong1993 已提交
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
            if val_repeats.dtype != 'int32':
                self.paddle_graph.add_layer(
                    "paddle.cast",
                    inputs={"x": repeats},
                    outputs=["{}.tmp".format(repeats)],
                    dtype=string("int32"))
                repeats = "{}.tmp".format(repeats)

        elif isinstance(repeats, int):
            repeats = [repeats]

        attr = {
            'expand_times': repeats,
S
SunAhong1993 已提交
1448
            "name": string(node.name),
S
SunAhong1993 已提交
1449 1450 1451
        }
        self.paddle_graph.add_layer(
            "paddle.tile", 
S
SunAhong1993 已提交
1452 1453
            inputs={"x": val_x.name}, 
                    outputs=[node.name], 
S
SunAhong1993 已提交
1454 1455 1456 1457 1458
                    repeat_times=repeats)

    @print_mapping_info
    def MaxPool(self, node):
        op_name = name_generator("pool", self.nn_name2id)
S
SunAhong1993 已提交
1459
        output_name = node.name
S
SunAhong1993 已提交
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
        layer_outputs = [op_name, output_name]
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        auto_pad = node.get_attr('auto_pad', 'NOTSET')
        assert node.get_attr(
            "dilations") is None, 'only dilations = 0 is supported'  # optional

        kernel_shape = node.get_attr("kernel_shape")
        poolnd = len(kernel_shape)
        strides = node.get_attr("strides")
        pad_mode = node.get_attr("pads")
        ceil_mode = bool(node.get_attr('ceil_mode', 0))  # optional
        pads = node.get_attr('pads', [0] * (poolnd * 2))  # optional
        paddle_op = 'paddle.nn.MaxPool{}D'.format(poolnd)
        assert 1 <= poolnd <= 3, 'only Pool1D, Pool2D and Pool3D are supported'

        paddings, val_x = self._pad_if_asymmetric(node, pads, val_x)

        if auto_pad == "SAME_UPPER" or auto_pad == "SAME_LOWER":
            input_shape = val_x.out_shapes[0]
            pad_h = _get_same_padding(input_shape[2], kernel_shape[0],
                                      strides[0])
            pad_w = _get_same_padding(input_shape[3], kernel_shape[1],
                                      strides[1])
            paddings = pad_h + pad_w
            
        layer_attrs = {
            "kernel_size": kernel_shape,
            "stride": strides,
            "padding": paddings,
            "ceil_mode": ceil_mode,
        }
        self.paddle_graph.add_layer(
            paddle_op, 
S
SunAhong1993 已提交
1493
            inputs={'x': val_x if isinstance(val_x, str) else val_x.name}, 
S
SunAhong1993 已提交
1494 1495 1496 1497 1498 1499
            outputs=layer_outputs, 
            **layer_attrs)

    @print_mapping_info
    def GlobalMaxPool(self, node):
        op_name = name_generator("pool", self.nn_name2id)
S
SunAhong1993 已提交
1500
        output_name = node.name
S
SunAhong1993 已提交
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
        layer_outputs = [op_name, output_name]
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        input_shape = val_x.out_shapes[0]
        if len(input_shape) == 4:
            poolnd = 2
        elif len(input_shape) == 5:
            poolnd = 3
        elif len(input_shape) == 3:
            poolnd = 1
        paddle_op = 'paddle.nn.AdaptiveMaxPool{}D'.format(poolnd)
        assert 1 <= poolnd <= 3, 'only Pool1D, Pool2D and Pool3D are supported'
        output_shape = node.out_shapes[0]
        self.paddle_graph.add_layer(
            paddle_op, 
S
SunAhong1993 已提交
1515
            inputs={'x': val_x.name}, 
S
SunAhong1993 已提交
1516 1517 1518 1519 1520 1521
            outputs=layer_outputs, 
            output_size=output_shape[2:])

    @print_mapping_info
    def GlobalAveragePool(self, node):
        op_name = name_generator("pool", self.nn_name2id)
S
SunAhong1993 已提交
1522
        output_name = node.name
S
SunAhong1993 已提交
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
        layer_outputs = [op_name, output_name]
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        input_shape = val_x.out_shapes[0]
        if len(input_shape) == 4:
            poolnd = 2
        elif len(input_shape) == 5:
            poolnd = 3
        elif len(input_shape) == 3:
            poolnd = 1
        paddle_op = 'paddle.nn.AdaptiveAvgPool{}D'.format(poolnd)
        assert 1 <= poolnd <= 3, 'only Pool1D, Pool2D and Pool3D are supported'
        output_shape = node.out_shapes[0]
        self.paddle_graph.add_layer(
            paddle_op, 
S
SunAhong1993 已提交
1537
            inputs={'x': val_x.name}, 
S
SunAhong1993 已提交
1538 1539 1540 1541 1542 1543
            outputs=layer_outputs, 
            output_size=output_shape[2:])

    @print_mapping_info
    def Conv(self, node):
        op_name = name_generator("conv", self.nn_name2id)
S
SunAhong1993 已提交
1544
        output_name = node.name
S
SunAhong1993 已提交
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
        layer_outputs = [op_name, output_name]
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_w = self.graph.get_input_node(node, idx=1, copy=True)
        has_bias = len(node.layer.input) == 3
        if has_bias:
            val_b = self.graph.get_input_node(node, idx=2, copy=True)
        auto_pad = node.get_attr('auto_pad', 'NOTSET')

        kernel_shape = node.get_attr('kernel_shape')
        convnd = len(kernel_shape)
        assert 2 <= convnd <= 3, 'only Conv2D and Conv3D is supported'
        num_out_channels = val_w.out_shapes[0][0]
        num_in_channels = val_w.out_shapes[0][1]
        paddle_op = 'paddle.nn.Conv{}D'.format(convnd)

        num_groups = node.get_attr('group', 1)
        strides = node.get_attr('strides', [1] * convnd)
        dilations = node.get_attr('dilations', [1] * convnd)
        pads = node.get_attr('pads', [0] * (convnd * 2))

        input_shape = val_x.out_shapes[0]
        paddings, val_x = self._pad_if_asymmetric(node, pads, val_x)

        if auto_pad == "SAME_UPPER" or auto_pad == "SAME_LOWER":
            pad_h = _get_same_padding(input_shape[2], kernel_shape[0],
                                      strides[0])
            pad_w = _get_same_padding(input_shape[3], kernel_shape[1],
                                      strides[1])
            paddings = pad_h + pad_w

        layer_attrs = {
            "in_channels": num_in_channels * num_groups,
            "out_channels": num_out_channels,
            "kernel_size": kernel_shape,
            "stride": strides,
            "padding": paddings,
            "dilation": dilations,
            "groups": num_groups,
S
SunAhong1993 已提交
1583
            'weight_attr': string(val_w.name),
S
SunAhong1993 已提交
1584 1585
        }
        if has_bias:
S
SunAhong1993 已提交
1586
            layer_attrs["bias_attr"] = string(val_b.name)
S
SunAhong1993 已提交
1587 1588 1589 1590
        else:
            layer_attrs["bias_attr"] = False
        self.paddle_graph.add_layer(
            paddle_op, 
S
SunAhong1993 已提交
1591
            inputs={'x': val_x if isinstance(val_x, str) else val_x.name}, 
S
SunAhong1993 已提交
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609
            outputs=layer_outputs, 
            **layer_attrs)

    @print_mapping_info
    def ConvTranspose(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_w = self.graph.get_input_node(node, idx=1, copy=True)
        val_b = None
        if len(node.layer.input) > 2:
            val_b = self.graph.get_input_node(node, idx=2, copy=True)
        auto_pad = node.get_attr('auto_pad', 'NOTSET')
        out_padding = node.get_attr('output_padding', [0, 0])
        kernel_shape = node.get_attr('kernel_shape')
        assert kernel_shape, 'kernel_shape not inferred'
        convnd = len(kernel_shape)
        assert 2 <= convnd <= 3, 'only Conv2DTranspose and Conv3DTranspose supported'
        num_in_channels = val_w.out_shapes[0][0]
        num_out_channels = val_w.out_shapes[0][1]
S
fix  
SunAhong1993 已提交
1610
        paddle_op = 'paddle.nn.functional.conv{}d_transpose'.format(convnd)
S
SunAhong1993 已提交
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627

        num_groups = node.get_attr('group', 1)
        strides = node.get_attr('strides', [1] * convnd)
        dilations = node.get_attr('dilations', [1] * convnd)
        output_size = node.get_attr('output_shape', [])
        pads = node.get_attr('pads', [0] * (convnd * 2))

        paddings, var_x = self._pad_if_asymmetric(node, pads, val_x)

        output_size = [0, 0]

        output_size[0] = (val_x.out_shapes[0][2] - 1
                          ) * strides[0] - 2 * paddings[0] + dilations[0] * (
                              kernel_shape[0] - 1) + 1 + out_padding[0]
        output_size[1] = (val_x.out_shapes[0][3] - 1
                          ) * strides[1] - 2 * paddings[1] + dilations[1] * (
                              kernel_shape[1] - 1) + 1 + out_padding[1]
S
fix  
SunAhong1993 已提交
1628 1629 1630
        # Conv2DTranspose缺少output_size,只能在forward里头传进output_size
        inputs_dict = {'x': val_x if isinstance(val_x, str) else val_x.name,
                       "weight": val_w.name}
S
SunAhong1993 已提交
1631
        layer_attrs = {
S
fix  
SunAhong1993 已提交
1632 1633 1634 1635 1636 1637 1638 1639 1640
            "stride": strides,
            "dilation": dilations,
            "padding": paddings,
            "groups": num_groups,
            "output_size": node.out_shapes[0][2:]}
        if val_b is not None:
            inputs_dict["bias"] = val_b.name
        else:
            layer_attrs["bias"] = None
S
SunAhong1993 已提交
1641
        self.paddle_graph.add_layer(
S
fix  
SunAhong1993 已提交
1642 1643 1644
            kernel="paddle.nn.functional.conv2d_transpose",
            inputs=inputs_dict,
            outputs=[node.name],
S
SunAhong1993 已提交
1645
            **layer_attrs)
S
SunAhong1993 已提交
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
        
    @print_mapping_info
    def ArgMax(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        axis = node.get_attr('axis')
        keepdims = False if node.get_attr('keepdims') == 0 else True
        layer_attrs = {'axis': axis,
                      'keepdim': keepdims}
        self.paddle_graph.add_layer(
            'paddle.argmax', 
            inputs={"x": val_x.name}, 
            outputs=[node.name],
            **layer_attrs)