opset.py 60.1 KB
Newer Older
1
# Copyright (c) 2019  PaddlePaddle Authors. All Rights Reserved.
C
update  
channingss 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14
#
# 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.

C
Channingss 已提交
15
from x2paddle.decoder.onnx_decoder import ONNXGraph, ONNXGraphNode, ONNXGraphDataNode
C
update  
channingss 已提交
16
from x2paddle.core.graph import GraphNode
C
channingss 已提交
17
from x2paddle.core.util import string
C
Channingss 已提交
18
from functools import reduce
C
update  
channingss 已提交
19
import numpy as np
C
channingss 已提交
20
import onnx
C
channingss 已提交
21
import onnx.numpy_helper as numpy_helper
C
channingss 已提交
22
from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE
C
update  
channingss 已提交
23
import logging as _logging
24
from collections import OrderedDict
C
channingss 已提交
25
import math
C
channingss 已提交
26
import os
S
SunAhong1993 已提交
27 28
import copy
import sys
C
channingss 已提交
29
import shutil
30

C
update  
channingss 已提交
31 32 33
_logger = _logging.getLogger(__name__)


C
Channingss 已提交
34
def _const_weight_or_none(node, necessary=False):
C
channings 已提交
35
    if 'Constant' in node.layer_type:
C
channingss 已提交
36
        return node.value
C
update  
channingss 已提交
37 38
    if isinstance(node, ONNXGraphDataNode):
        return node.weight
C
Channingss 已提交
39 40 41
    if necessary:
        assert '{} should be an initializer or Constant operator.'.format(
            node.layer_name)
C
update  
channingss 已提交
42 43 44
    return None


C
Channingss 已提交
45 46 47 48 49 50
def _is_static_shape(shape):
    negtive_dims = 0
    error_dims = 0
    for dim in shape:
        if dim < 0:
            negtive_dims += 1
C
update  
Channingss 已提交
51
        if dim < -1:
C
Channingss 已提交
52 53 54 55 56 57 58
            error_dims += 1
    if negtive_dims > 1:
        return False
    if error_dims > 0:
        return False
    return True

59

C
Channingss 已提交
60
def _get_same_padding(in_size, kernel_size, stride):
C
channingss 已提交
61 62 63 64 65 66 67
    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]


68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
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(
                node.layer_name[9:], node.layer_type))
            raise
        else:
            #print("convert successfully node:{}, op_type is {}".format(
            #    node.layer_name[9:], node.layer_type))
            return res

    return run_mapping


C
Channingss 已提交
85
class OpSet9():
86
    elementwise_ops = {
S
SunAhong1993 已提交
87 88
        'Add': 'paddle.add',
        'Div': 'paddle.divide',
S
fix  
SunAhong1993 已提交
89
        'Sub': 'paddle.subtract',
S
SunAhong1993 已提交
90 91
        'Mul': 'paddle.multiply',
        'Pow': 'paddle.pow',
R
root 已提交
92
    }
93

S
SunAhong1993 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    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.functional.relu'],
        'LeakyRelu': ['paddle.nn.functional.leaky_relu', 
                      dict(alpha='negative_slope'), 
                      dict(negative_slope=.01)],
        'Elu': ['paddle.nn.functional.elu', 
                dict(alpha='alpha'), 
                dict(alpha=1.)],
        'ThresholdedRelu': ['paddle.nn.functional.thresholded_relu', 
                            dict(alpha='threshold'),
                            dict(alpha=1.)],
        'Tanh': ['paddle.nn.functional.tanh'],
        'Sigmoid': ['paddle.nn.functional.sigmoid'],
        'Softsign': ['paddle.nn.functional.softsign'],
        'Softplus': ['paddle.nn.functional.softplus', 
                     dict(threshold='threshold'), 
                     dict(threshold=float(sys.maxsize))],
        'Exp': ['paddle.exp'],
        'Softmax': ['paddle.nn.functional.softmax', 
                    dict(axis='axis'), 
                    dict(axis=1)],
        'Sqrt': ['paddle.sqrt'],
        'Floor': ['paddle.floor'],
        'Abs': ['paddle.abs'],
        'Erf': ['paddle.erf'],
134 135
    }

S
SunAhong1993 已提交
136
    def __init__(self, decoder, paddle_graph):
C
Channingss 已提交
137
        super(OpSet9, self).__init__()
138
        self.graph = decoder.graph
S
SunAhong1993 已提交
139 140 141 142
        self.paddle_graph = paddle_graph
        self.input_index = 0
        self.inputs_info = dict()
        self.params = dict()
R
root 已提交
143

144
    @print_mapping_info
S
SunAhong1993 已提交
145
    def directly_map(self, node, *args, **kwargs):
C
update  
channingss 已提交
146
        inputs = node.layer.input
S
SunAhong1993 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
        assert len(inputs) == 1, 'directly_map error with multi inputs'
        input = self.graph.get_input_node(node, idx=0, copy=True)
        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]
        self.paddle_graph.add_layer(
            kernel=paddle_op,
            inputs={"x": input.name},
            outputs=[node.name],
            **layer_attrs)
            
170
    @print_mapping_info
171 172 173 174
    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 已提交
175 176 177 178 179 180 181
        inputs_dict = {'x': val_x.name, 
                       'y': val_y.name}
        self.paddle_graph.add_layer(
            op_type, 
            inputs=inputs_dict, 
            outputs=[node.name])
        
182
    @print_mapping_info
C
update  
channingss 已提交
183
    def place_holder(self, node):
C
channings 已提交
184 185
        shape = node.out_shapes[0]
        for i, dim_shape in enumerate(shape):
R
root 已提交
186 187 188
            if dim_shape == 0 and i == 0:
                shape[i] = 1
            if dim_shape == 0 and i != 0:
C
channings 已提交
189
                assert 'shape of input is not assigned'
S
SunAhong1993 已提交
190 191 192 193 194 195 196 197 198
        self.paddle_graph.add_layer(
            kernel="paddle.static.data",
            inputs={},
            outputs=[node.name],
            dtype=string(node.dtype),
            shape=shape,
            name=string(node.name))
        self.inputs_info["x{}".format(self.input_index)] = [shape, node.dtype]
        self.input_index += 1
C
update  
channingss 已提交
199

200
    @print_mapping_info
C
update  
channingss 已提交
201 202 203 204
    def create_parameter(self, node, parameter=None):
        if parameter is not None:
            node = parameter
        dtype = node.dtype
C
channingss 已提交
205
        shape = node.out_shapes[0]
C
channingss 已提交
206
        if len(node.weight.shape) == 0:
S
SunAhong1993 已提交
207 208 209 210 211 212 213
            self.paddle_graph.add_layer(
                "paddle.full", 
                inputs={}, 
                outputs=[node.name],
                dtype=string(dtype),
                shape=[1],
                fill_value=node.weight)
214
        else:
S
SunAhong1993 已提交
215 216 217 218 219 220 221 222 223
            self.params[node.name] = node.weight
            self.paddle_graph.add_layer(
                kernel="paddle.static.create_parameter",
                inputs={},
                outputs=[node.name],
                dtype=string(dtype),
                shape=shape,
                name=string(node.name),
                default_initializer="paddle.nn.initializer.Constant(value=0.0)")
C
update  
channingss 已提交
224 225 226 227 228 229 230 231 232 233 234 235 236 237

    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

C
channingss 已提交
238
    def _interpolate(self, node):
C
channingss 已提交
239
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
240
        inputs = {'x': val_x.name}
S
fix  
SunAhong1993 已提交
241
        attrs = dict()
242
        if node.layer_type == 'Resize':
C
Channingss 已提交
243 244 245
            if len(node.layer.input) == 2:
                # opset 10
                val_scales = self.graph.get_input_node(node, idx=1, copy=True)
S
fix  
SunAhong1993 已提交
246 247 248 249
                # TODO(syf): paddle.nn.functional.interpolate will support the length  
                # which is the same as the rank of input.
#                 inputs['scale_factor'] = val_scales.name
                attrs['scale_factor'] = self.params[val_scales.name].tolist()[2:]
C
Channingss 已提交
250 251 252
            elif len(node.layer.input) == 3:
                # opset 11
                val_scales = self.graph.get_input_node(node, idx=2, copy=True)
S
fix  
SunAhong1993 已提交
253 254 255 256
                # TODO(syf): paddle.nn.functional.interpolate will support the length  
                # which is the same as the rank of input.
#                 inputs['scale_factor'] = val_scales.name
                attrs['scale_factor'] = self.params[val_scales.name].tolist()[2:]
C
Channingss 已提交
257 258 259
            elif len(node.layer.input) == 4:
                # opset 11
                val_sizes = self.graph.get_input_node(node, idx=3, copy=True)
S
SunAhong1993 已提交
260 261 262 263 264 265 266 267 268 269 270 271
                var_nc, var_hw = val_sizes.name + '_nc', val_sizes.name + '_hw'
                self.paddle_graph.add_layer(
                    'paddle.split',
                    inputs={"x": val_sizes.name},
                    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 已提交
272 273 274
                inputs['size'] = var_hw
                attrs = {"align_corners": False,
                         "mode": string(node.get_attr('mode', 'nearest'))}
S
SunAhong1993 已提交
275
                self.paddle_graph.add_layer(
S
docs  
SunAhong1993 已提交
276
                    kernel="paddle.nn.functional.interpolate",
S
SunAhong1993 已提交
277 278 279 280
                    inputs=inputs,
                    outputs=[node.name],
                    **attrs)
                return
281 282
        elif node.layer_type == 'Upsample':
            val_scales = self.graph.get_input_node(node, idx=1, copy=True)
C
Channingss 已提交
283
            inputs['scale'] = val_scales
R
root 已提交
284

C
channingss 已提交
285
        mode = node.get_attr('mode', 'nearest')
S
fix  
SunAhong1993 已提交
286
        attrs.update({"align_corners": False,
S
SunAhong1993 已提交
287
                 "mode": string(mode),
S
fix  
SunAhong1993 已提交
288
                 "align_mode": 1})
S
SunAhong1993 已提交
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
        self.paddle_graph.add_layer(
            kernel="paddle.nn.functional.interpolate",
            inputs=inputs,
            outputs=[node.name],
            **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",
            inputs={"x": val_x.name},
            outputs=[node.name + "_val"],
            scale=alpha,
            bias=beta)
        self.paddle_graph.add_layer(
            kernel="paddle.clip",
            inputs={"x": node.name + "_val"},
            outputs=[node.name],
            min=0.0,
            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'))   
R
root 已提交
325

326
    @print_mapping_info
C
channings 已提交
327 328 329
    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)
R
root 已提交
330 331 332

        pooled_height = node.get_attr('output_height')
        pooled_width = node.get_attr('output_width')
C
channings 已提交
333 334
        spatial_scale = node.get_attr('spatial_scale')
        sampling_ratio = node.get_attr('sampling_ratio')
S
SunAhong1993 已提交
335
        layer_attrs = {
R
root 已提交
336 337 338 339 340
            'pooled_height': pooled_height,
            'pooled_width': pooled_width,
            'spatial_scale': spatial_scale,
            'sampling_ratio': sampling_ratio,
        }
S
SunAhong1993 已提交
341
        self.paddle_graph.add_layer(
S
SunAhong1993 已提交
342
            'paddle.fluid.layers.roi_align',
S
SunAhong1993 已提交
343 344 345 346
            inputs={'input': val_x.name,
                    'rois': val_rois.name},
            outputs=[node.name],
            **layer_attrs)
347 348

    @print_mapping_info
C
channings 已提交
349 350 351
    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)
R
root 已提交
352

C
channings 已提交
353 354
        spatial_scale = node.get_attr('spatial_scale')
        pooled_height, pooled_width = node.get_attr('pooled_shape')
S
SunAhong1993 已提交
355
        layer_attrs = {
R
root 已提交
356 357 358 359
            'pooled_height': pooled_height,
            'pooled_width': pooled_width,
            'spatial_scale': spatial_scale,
        }
S
SunAhong1993 已提交
360
        self.paddle_graph.add_layer(
S
SunAhong1993 已提交
361
            'paddle.fluid.layers.roi_pool',
S
SunAhong1993 已提交
362 363 364 365
            inputs={'input': val_x.name,
                    'rois': val_rois.name},
            outputs=[node.name],
            **layer_attrs)
366 367

    @print_mapping_info
C
update  
channingss 已提交
368
    def Pad(self, node, op_independent=True):
C
channingss 已提交
369
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
C
update  
channingss 已提交
370 371 372
        pads = node.get_attr('pads')
        mode = node.get_attr('mode', 'constant')
        value = node.get_attr('value', 0.)
C
channingss 已提交
373 374
        data_shape = val_x.out_shapes[0]
        output_shape = node.out_shapes[0]
C
update  
channingss 已提交
375
        assume_pad2d = False
S
SunAhong1993 已提交
376 377
        layer_attrs = {}
        layer_attrs['mode'] = string(mode)
C
channings 已提交
378
        paddings = []
C
update  
channingss 已提交
379 380 381 382 383 384 385
        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:
S
SunAhong1993 已提交
386 387 388
            paddle_op = 'paddle.nn.functional.pad'
            layer_attrs['data_format'] = string('NCHW')
            layer_attrs['value'] = value
C
update  
channingss 已提交
389
        else:
S
SunAhong1993 已提交
390
            paddle_op = 'paddle.fluid.layers.pad'
S
SunAhong1993 已提交
391
            layer_attrs["pad_value"] = value
C
update  
channingss 已提交
392 393 394 395 396 397
        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
C
channingss 已提交
398
            if sum(paddings[:4]) == 0:
S
SunAhong1993 已提交
399
                paddle_op = 'paddle.nn.functional.pad'
C
channingss 已提交
400
                paddings = paddings[4:]
S
SunAhong1993 已提交
401 402 403 404 405 406 407 408 409 410 411 412
                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.functional.pad':
            layer_attrs['pad'] = paddings
        else:
            layer_attrs['paddings'] = paddings
C
update  
channingss 已提交
413
        if op_independent:
S
SunAhong1993 已提交
414 415 416 417 418
            self.paddle_graph.add_layer(
                paddle_op, 
                inputs={'x': val_x.name}, 
                outputs=[node.name], 
                **layer_attrs)
C
update  
channingss 已提交
419
        else:
S
SunAhong1993 已提交
420 421 422 423 424 425
            self.paddle_graph.add_layer(
                paddle_op,
                inputs={'x': val_x.name},
                outputs=[node.name + '_paded'],
                **layer_attrs)
            return node.name + '_paded'
C
update  
channingss 已提交
426

427
    @print_mapping_info
C
update  
channingss 已提交
428
    def Unsqueeze(self, node):
C
channingss 已提交
429
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
C
update  
channingss 已提交
430
        axes = node.get_attr('axes')
S
SunAhong1993 已提交
431
        layer_attrs = {'axis': axes}
R
root 已提交
432
        if len(val_x.out_shapes[0]) == 0:
S
SunAhong1993 已提交
433 434 435 436 437 438
            if node.name:
                self.paddle_graph.add_layer(
                    'paddle.reshape',
                    inputs={"x": val_x.name},
                    outputs=[node.name],
                    shape=[1])
439
        else:
S
SunAhong1993 已提交
440 441 442 443 444
            self.paddle_graph.add_layer(
                'paddle.unsqueeze', 
                inputs={"x": val_x.name}, 
                outputs=[node.name],
                **layer_attrs)
445

446
    @print_mapping_info
C
channingss 已提交
447
    def Shrink(self, node):
C
channingss 已提交
448
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
C
channingss 已提交
449 450 451
        bias = node.get_attr('bias')
        lambd = node.get_attr('lambd')
        assert bias == 0.0, 'not support bias!=0'
S
SunAhong1993 已提交
452 453 454 455 456
        self.paddle_graph.add_layer(
            'paddle.nn.functional.hardshrink', 
            inputs={"x": val_x.name}, 
            outputs=[node.name], 
            threshold=lambd)
C
channingss 已提交
457

458
    @print_mapping_info
C
update  
channingss 已提交
459 460 461 462 463 464 465 466
    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'
R
root 已提交
467

C
update  
channingss 已提交
468
        shape = node.get_attr('shape', None)
R
root 已提交
469

C
update  
channingss 已提交
470
        if shape is None:
C
channingss 已提交
471
            shape = val_output.out_shapes[0]
C
update  
channingss 已提交
472 473
        if shape is None:
            shape = list(value.shape)
474 475 476
            _logger.warning('in (Constant -> %s): '
                            'attribute "shape" of %s not inferred, '
                            'using value as 1-D tensor may lead to fails',
S
SunAhong1993 已提交
477
                            val_output.name, val_output.name)
478
        if len(value) == 1:
C
channingss 已提交
479
            value = value.tolist()
C
update  
channingss 已提交
480
            value = value[0]
S
SunAhong1993 已提交
481 482 483 484 485 486 487
            self.paddle_graph.add_layer(
                "paddle.full", 
                inputs={}, 
                outputs=[node.name],
                dtype=string(dtype),
                shape=[1],
                fill_value=value)
C
channingss 已提交
488 489
        else:
            value = np.reshape(value, shape)
S
SunAhong1993 已提交
490 491 492 493 494 495 496 497 498
            self.params[node.name] = value
            self.paddle_graph.add_layer(
                kernel="paddle.static.create_parameter",
                inputs={},
                outputs=[node.name],
                dtype=string(dtype),
                shape=shape,
                name=string(node.name),
                default_initializer="paddle.nn.initializer.Constant(value=0.0)")
C
update  
channingss 已提交
499

500
    @print_mapping_info
C
update  
channingss 已提交
501
    def Resize(self, node):
502 503
        self._interpolate(node)

504
    @print_mapping_info
505 506 507
    def Upsample(self, node):
        self._interpolate(node)

508 509 510 511 512 513
    @print_mapping_info
    def InstanceNormalization(self, node):
        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)
S
SunAhong1993 已提交
514
        layer_attrs = {
S
fix  
SunAhong1993 已提交
515
            'eps': epsilon,
516
        }
S
SunAhong1993 已提交
517 518
        dim = len(val_x.out_shapes[0])
        if dim ==2 :
S
fix  
SunAhong1993 已提交
519
            layer_attrs["data_format"] = string("NC")
S
SunAhong1993 已提交
520
        elif dim == 3:
S
fix  
SunAhong1993 已提交
521
            layer_attrs["data_format"] = string("NCL")
S
SunAhong1993 已提交
522
        elif dim == 4:
S
fix  
SunAhong1993 已提交
523
            layer_attrs["data_format"] = string("NCHW")
S
SunAhong1993 已提交
524
        elif dim == 5:
S
fix  
SunAhong1993 已提交
525
            layer_attrs["data_format"] = string("NCDHW")
S
SunAhong1993 已提交
526 527 528
        else:
            raise Exception("The paddle only support 2D, 3D, 4D or 5D input in InstanceNormalization.")
        self.paddle_graph.add_layer(
S
fix  
SunAhong1993 已提交
529
            "paddle.nn.functional.instance_norm", 
S
SunAhong1993 已提交
530 531 532
            inputs={"x": val_x.name,
                    "weight": val_scale.name,
                    "bias": val_b.name}, 
S
fix  
SunAhong1993 已提交
533
            outputs=[node.name], 
S
SunAhong1993 已提交
534
            **layer_attrs)
535 536

    @print_mapping_info
537
    def Expand(self, node):
C
channingss 已提交
538
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
539
        val_shape = self.graph.get_input_node(node, idx=1, copy=True)
540
        val_x_dtype = val_x.dtype
S
SunAhong1993 已提交
541
        name_ones = node.name + '_ones'
C
Channingss 已提交
542
        attr_ones = {
S
SunAhong1993 已提交
543
            'shape': val_shape.name,
C
Channingss 已提交
544
            'dtype': string(val_x_dtype),
S
SunAhong1993 已提交
545
            'fill_value': 1
C
Channingss 已提交
546
        }
S
SunAhong1993 已提交
547 548 549 550 551 552 553 554 555 556 557
        self.paddle_graph.add_layer(
            'paddle.full',
            inputs={},
            outputs=[name_ones],
            **attr_ones)
        inputs_dict = {'x': name_ones, 
                       'y': val_x.name}
        self.paddle_graph.add_layer(
            'paddle.multiply',
            inputs=inputs_dict,
            outputs=[node.name])
C
update  
channingss 已提交
558

559
    @print_mapping_info
C
channingss 已提交
560 561 562 563
    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]
C
Channingss 已提交
564
        axis = node.get_attr('axis', 0)
565 566
        #assert len(
        #    indices_shape) <= 2, "Gather op don't support dim of indice >2 "
R
root 已提交
567
        if axis == 0 and len(indices_shape) <= 1:
C
Channingss 已提交
568
            if len(val_x.out_shapes[0]) <= 1:
S
SunAhong1993 已提交
569 570 571 572 573
                self.paddle_graph.add_layer(
                    'paddle.gather',
                    inputs={'x': val_x.name,
                            'index': indices.name},
                    outputs=[node.name])
C
Channingss 已提交
574 575
            elif len(val_x.out_shapes[0]) > 1:
                if len(indices_shape) == 0:
S
SunAhong1993 已提交
576 577 578 579 580 581 582 583 584 585 586
                    gather_ = node.name + '_1'
                    self.paddle_graph.add_layer(
                        'paddle.gather',
                        inputs={'x': val_x.name,
                                'index': indices.name},
                        outputs=[gather_])
                    self.paddle_graph.add_layer(
                        'paddle.squeeze',
                        inputs={'x': gather_},
                        outputs=[node.name],
                        axis=[0])
C
Channingss 已提交
587
                else:
S
SunAhong1993 已提交
588 589 590 591 592
                    self.paddle_graph.add_layer(
                        'paddle.gather',
                        inputs={'x': val_x.name,
                                'index': indices.name},
                        outputs=[node.name])
C
channingss 已提交
593 594
        elif axis > 0 and len(indices_shape) <= 1:
            perm = list(range(len(val_x.out_shapes[0])))
C
channingss 已提交
595
            perm = [axis] + perm[:axis] + perm[axis + 1:]
S
SunAhong1993 已提交
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
            name_trans = val_x.name + '_trans'
            self.paddle_graph.add_layer(
                'paddle.transpose',
                inputs={"x": val_x.name},
                outputs=[name_trans],
                perm=perm)
            self.paddle_graph.add_layer(
                'paddle.gather',
                inputs={'x': name_trans,
                        'index': indices.name},
                outputs=[node.name])
            self.paddle_graph.add_layer(
                'paddle.transpose', 
                inputs={"x": node.name}, 
                outputs=[node.name], 
                perm=perm)
C
Channingss 已提交
612
            if len(indices_shape) < 1:
S
SunAhong1993 已提交
613 614 615 616 617
                self.paddle_graph.add_layer(
                    'paddle.squeeze',
                    inputs={'x': node.name},
                    outputs=[node.name],
                    axis=[axis])
618 619 620
        elif axis == 0 and len(indices_shape) > 1:
            if val_x.out_shapes[0] is not None and isinstance(
                    val_x, ONNXGraphDataNode):
S
SunAhong1993 已提交
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
                indices_cast = indices.name + '_cast'
                self.paddle_graph.add_layer(
                    'paddle.cast',
                    inputs={"x": indices.name},
                    outputs=indices_cast,
                    dtype=string('int64'))
                op_name = name_generator("embedding", self.nn_name2id)
                output_name = node.name
                layer_outputs = [op_name, output_name]
                self.paddle_graph.add_layer(
                    'paddle.nn.Embedding',
                    inputs={"x": indices_cast},
                    outputs=layer_outputs,
                    param_attr=string(val_x.name),
                    size=val_x.out_shapes[0])
636 637 638
            else:
                from functools import reduce
                reshape_shape = reduce(lambda x, y: x * y, indices_shape)
S
SunAhong1993 已提交
639 640 641 642 643 644
                indices_reshape = indices.name + '_shape'
                self.paddle_graph.add_layer(
                    'paddle.reshape',
                    inputs={"x": indices.name},
                    outputs=[indices_reshape],
                    shape=[reshape_shape, ])
645 646

                perm = list(range(len(val_x.out_shapes[0])))
S
SunAhong1993 已提交
647 648 649
                self.paddle_graph.add_layer(
                    'paddle.gather',
                    inputs={'x': val_x.name,
650
                            'index': indices_reshape},
S
SunAhong1993 已提交
651
                    outputs=[node.name])
652 653 654 655 656 657
                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)
S
SunAhong1993 已提交
658 659 660 661 662
                self.paddle_graph.add_layer(
                    'paddle.reshape',
                    inputs={"x": node.name},
                    outputs=[node.name],
                    shape=reshaped_shape)
663
        elif axis > 0 and len(indices_shape) > 1:
C
Channingss 已提交
664
            from functools import reduce
R
root 已提交
665
            reshape_shape = reduce(lambda x, y: x * y, indices_shape)
S
SunAhong1993 已提交
666 667 668 669 670 671
            indices_reshape = indices.name + '_shape'
            self.paddle_graph.add_layer(
                'paddle.reshape',
                inputs={"x": indices.name},
                outputs=[indices_reshape],
                shape=[reshape_shape, ])
R
root 已提交
672

C
Channingss 已提交
673 674
            perm = list(range(len(val_x.out_shapes[0])))
            perm = [axis] + perm[:axis] + perm[axis + 1:]
S
SunAhong1993 已提交
675 676 677 678 679 680 681 682 683
            name_trans = val_x.name + '_transpose'
            self.paddle_graph.add_layer(
                'paddle.transpose',
                inputs={"x": val_x.name},
                outputs=[name_trans],
                perm=perm)
            self.paddle_graph.add_layer(
                'paddle.gather',
                inputs={'x': name_trans,
684
                        'index': indices_reshape},
S
SunAhong1993 已提交
685 686 687 688 689 690 691
                outputs=[node.name])
            input_transpose = node.name + '_transpose'
            self.paddle_graph.add_layer(
                'paddle.transpose',
                inputs={"x": node.name},
                outputs=[input_transpose],
                perm=perm)
C
Channingss 已提交
692 693 694 695 696 697
            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)
S
SunAhong1993 已提交
698 699 700 701 702
            self.paddle_graph.add_layer(
                'paddle.reshape',
                inputs={"x": input_transpose},
                outputs=[node.name],
                shape=reshaped_shape)
703

C
Channingss 已提交
704 705 706 707 708 709
    @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:
S
SunAhong1993 已提交
710 711 712 713 714 715
            self.paddle_graph.add_layer(
                'paddle.scatter',
                inputs={'x': val_x.name,
                        'index': indices.name,
                        'updates': updates.name},
                outputs=[node.name])
C
Channingss 已提交
716
        else:
S
SunAhong1993 已提交
717
            input_inner_indices = node.name + '_input_inner_indices'
718
            shape = val_x.out_shapes[0]
S
SunAhong1993 已提交
719 720 721 722 723 724 725 726 727 728 729 730 731
            self.paddle_graph.add_layer(
                'paddle.reshape',
                inputs={"x": indices.name},
                outputs=[indices.name],
                shape=indices.out_shapes[0])

            zeros_like_val_x = val_x.name + '_zeros'
            self.paddle_graph.add_layer(
                'paddle.zeros_like',
                inputs={"x": val_x.name},
                outputs=[zeros_like_val_x])
            self.paddle_graph.add_layer(
                'paddle.scatter_nd_add',
C
Channingss 已提交
732
                inputs={
S
SunAhong1993 已提交
733 734 735
                    'x': zeros_like_val_x,
                    'index': indices.name,
                    'updates': updates.name
C
Channingss 已提交
736
                },
S
SunAhong1993 已提交
737 738 739
                outputs=[input_inner_indices])
            indices_mask = node.name + '_indices_mask'
            constant_minus_one = node.name + '_constant_minus_one'
740
            # full_like support create tensor shape like input tensor
S
SunAhong1993 已提交
741 742 743 744 745 746 747 748
            self.paddle_graph.add_layer(
                'paddle.full_like',
                inputs={"x": updates.name},
                outputs=[constant_minus_one],
                dtype=string(updates.dtype),
                fill_value=-1)
            self.paddle_graph.add_layer(
                'paddle.scatter_nd_add',
C
Channingss 已提交
749
                inputs={
S
SunAhong1993 已提交
750 751
                    'x': zeros_like_val_x,
                    'index': indices.name,
C
Channingss 已提交
752 753
                    'updates': constant_minus_one
                },
S
SunAhong1993 已提交
754 755
                outputs=[indices_mask])
            constant_one = node.name + '_constant_1'
756
            # full_like support create tensor shape like input tensor
S
SunAhong1993 已提交
757 758 759 760 761 762 763 764 765
            self.paddle_graph.add_layer(
                'paddle.full_like',
                inputs={"x": val_x.name},
                outputs=[constant_one],
                dtype=string(val_x.dtype),
                fill_value=1)
            input_out_indices_mask = node.name + '_input_out_indices_mask'
            self.paddle_graph.add_layer(
                "paddle.add",
C
Channingss 已提交
766
                inputs={"x": indices_mask,
767
                        "y": constant_one},
S
SunAhong1993 已提交
768
                outputs=[input_out_indices_mask])
C
Channingss 已提交
769

S
SunAhong1993 已提交
770 771 772 773
            input_out_indices = node.name + '_input_out_indices'
            self.paddle_graph.add_layer(
                "paddle.multiply",
                inputs={"x": val_x.name,
C
Channingss 已提交
774
                        "y": input_out_indices_mask},
S
SunAhong1993 已提交
775
                outputs=[input_out_indices])
C
Channingss 已提交
776

S
SunAhong1993 已提交
777 778
            self.paddle_graph.add_layer(
                "paddle.add",
C
Channingss 已提交
779 780
                inputs={"x": input_inner_indices,
                        "y": input_out_indices},
S
SunAhong1993 已提交
781
                outputs=[node.name])
C
Channingss 已提交
782

783 784 785 786 787 788
    @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 已提交
789 790 791 792 793
        inputs = {'start': val_start.name, 
                  'end': val_limit.name, 
                  'step': val_delta.name}
        self.paddle_graph.add_layer(
            'paddle.arange',
794
            inputs=inputs,
S
SunAhong1993 已提交
795 796
            outputs=[node.name],
            dtype=string(dtype))
797 798

    @print_mapping_info
C
channingss 已提交
799
    def Slice(self, node):
C
channingss 已提交
800
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
C
channings 已提交
801
        starts, ends, axes, steps = None, None, None, None
S
SunAhong1993 已提交
802
        layer_attrs = {}
C
channingss 已提交
803 804 805
        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)
C
Channingss 已提交
806 807 808
            starts_value = _const_weight_or_none(starts)
            ends_value = _const_weight_or_none(ends)

R
root 已提交
809
            if len(node.inputs) > 3:
C
channings 已提交
810
                axes = self.graph.get_input_node(node, idx=3, copy=True)
C
Channingss 已提交
811
                axes = _const_weight_or_none(axes, necessary=True)
R
root 已提交
812
            if len(node.inputs) > 4:
C
channings 已提交
813
                steps = self.graph.get_input_node(node, idx=4, copy=True)
C
update  
Channingss 已提交
814
                steps = _const_weight_or_none(steps)
S
SunAhong1993 已提交
815
            layer_attrs = {
816
                "axes": axes,
S
SunAhong1993 已提交
817 818
                "starts": starts.name,
                "ends": ends.name
819 820
            }
            if starts_value is not None and ends_value is not None:
C
Channingss 已提交
821
                starts_value = starts_value.copy()
822
                ends_value = ends_value.copy()
823 824 825 826
                #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)
827
                for idx in range(len(ends_value)):
828 829
                    if starts_value[idx] >= val_x.out_shapes[0][axes[idx]]:
                        starts_value[idx] = val_x.out_shapes[0][axes[idx]] - 1
C
Channingss 已提交
830
                        ends_value[idx] = val_x.out_shapes[0][axes[idx]]
831
                        starts_value[idx] = val_x.out_shapes[0][axes[idx]] - 1
C
Channingss 已提交
832
                    elif ends_value[idx] > 2**31 - 1:
833
                        ends_value[idx] = 2**31 - 1
S
SunAhong1993 已提交
834
                layer_attrs = {
835 836 837 838 839 840
                    "axes": axes,
                    "starts": starts_value,
                    "ends": ends_value
                }
            else:
                if starts.dtype != 'int32':
S
SunAhong1993 已提交
841 842 843 844 845 846 847
                    starts_cast = starts.name + '_cast'
                    self.paddle_graph.add_layer(
                        'paddle.cast',
                        inputs={"x": starts.name},
                        outputs=[starts_cast],
                        dtype=string('int32'))
                    layer_attrs['starts'] = starts_cast
848
                if ends.dtype != 'int32':
S
SunAhong1993 已提交
849 850 851 852 853 854 855
                    ends_cast = ends.name + '_cast'
                self.paddle_graph.add_layer(
                    'paddle.cast',
                    inputs={"x": ends.name},
                    outputs=[ends_cast],
                    dtype=string('int32'))
                layer_attrs['ends'] = ends_cast
C
channingss 已提交
856 857 858 859
        else:
            starts = node.get_attr('starts')
            ends = node.get_attr('ends')
            axes = node.get_attr('axes')
860 861 862
            for idx in range(len(ends)):
                if ends[idx] > 2**31 - 1:
                    ends[idx] = 2**31 - 1
S
SunAhong1993 已提交
863
            layer_attrs = {"axes": axes, "starts": starts, "ends": ends}
C
channingss 已提交
864

C
Channingss 已提交
865
        if steps is not None:
S
SunAhong1993 已提交
866 867 868 869 870 871
            layer_attrs['strides'] = steps
            self.paddle_graph.add_layer(
                'paddle.strided_slice', 
                inputs={"x": val_x.name}, 
                outputs=[node.name], 
                **layer_attrs)
C
Channingss 已提交
872
        else:
S
SunAhong1993 已提交
873 874 875 876 877
            self.paddle_graph.add_layer(
                'paddle.slice', 
                inputs={"input": val_x.name}, 
                outputs=[node.name],  
                **layer_attrs)
C
channingss 已提交
878

879
    @print_mapping_info
C
update  
channingss 已提交
880
    def ConstantOfShape(self, node):
C
channingss 已提交
881
        val_shape = self.graph.get_input_node(node, idx=0, copy=True)
C
channingss 已提交
882
        val_y = self.graph.get_node(node.layer.output[0], copy=True)
C
update  
channingss 已提交
883 884 885 886

        value = node.get_attr('value')
        dtype = value.dtype
        value = value.tolist()
887 888
        assert len(value) == 1, ('given value not Scalar, shape of value > 1, '
                                 'this is not supported')
C
update  
channingss 已提交
889 890
        if len(value) == 1:
            value = value[0]
S
SunAhong1993 已提交
891 892
            layer_attrs = {
                'shape': val_shape.name,
893
                'dtype': string(dtype),
S
SunAhong1993 已提交
894
                'fill_value': value
895
            }
S
SunAhong1993 已提交
896 897 898 899 900
            self.paddle_graph.add_layer(
                "paddle.full", 
                inputs={}, 
                outputs=[node.name],
                **layer_attrs)
C
update  
channingss 已提交
901

C
Channingss 已提交
902 903 904 905 906 907 908 909
    @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')
S
SunAhong1993 已提交
910
            layer_attrs = {
C
Channingss 已提交
911 912 913
                'max': max_value,
                'min': min_value,
            }
S
SunAhong1993 已提交
914 915 916 917 918
            self.paddle_graph.add_layer(
                'paddle.clip', 
                inputs={"x": val_x.name}, 
                outputs=[node.name], 
                **layer_attrs)
C
Channingss 已提交
919
        else:
S
fix  
SunAhong1993 已提交
920 921
            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 已提交
922
            min_value = _const_weight_or_none(min_ipt)
S
fix  
SunAhong1993 已提交
923
            max_value = _const_weight_or_none(max_ipt)
924
            if max_value.shape == (1, ):
C
Channingss 已提交
925
                max_value = max_value[0]
926
            if min_value.shape == (1, ):
C
Channingss 已提交
927 928
                min_value = min_value[0]
        if max_value is not None and min_value is not None:
S
SunAhong1993 已提交
929 930 931 932 933 934
            layer_attrs = {'max': max_value, 'min': min_value}
            self.paddle_graph.add_layer(
                'paddle.clip', 
                inputs={"x": val_x.name}, 
                outputs=[node.name], 
                **layer_attrs)
C
Channingss 已提交
935 936 937
        else:
            raise

938
    @print_mapping_info
C
update  
channingss 已提交
939
    def Split(self, node):
C
channingss 已提交
940
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
941
        paddle_op = 'split'
C
channingss 已提交
942
        split = node.get_attr('split')
C
update  
channingss 已提交
943
        axis = node.get_attr('axis', 0)
S
SunAhong1993 已提交
944
        layer_attrs = {
C
channingss 已提交
945
            'num_or_sections': split,
S
SunAhong1993 已提交
946
            'axis': axis,
C
channingss 已提交
947
        }
S
SunAhong1993 已提交
948 949 950 951 952 953 954 955 956 957 958
        outputs_list = list()
        if isinstance(split, list) or isinstance(split, tuple):
            for i in range(len(split)):
                outputs_list.append("{}_p{}".format(node.layer_name, i))
        else:
            outputs_list.append(node.name)
        self.paddle_graph.add_layer(
            'paddle.split', 
            inputs={"x": val_x.name}, 
            outputs=outputs_list, 
            **layer_attrs)
C
update  
channingss 已提交
959

960
    @print_mapping_info
C
update  
channingss 已提交
961
    def Reshape(self, node):
C
channingss 已提交
962 963
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_shape = self.graph.get_input_node(node, idx=1, copy=True)
C
update  
channingss 已提交
964
        val_reshaped = self.graph.get_node(node.layer.output[0], copy=True)
965 966 967 968
        shape_value = _const_weight_or_none(val_shape)
        shape_dims = len(val_shape.out_shapes[0])

        if shape_value is not None:
S
SunAhong1993 已提交
969 970 971 972 973
            self.paddle_graph.add_layer(
                'paddle.reshape',
                inputs={'x': val_x.name},
                outputs=[node.name],
                shape=shape_value.tolist())
C
Channingss 已提交
974 975
        elif len(node.out_shapes[0]) > 0 and _is_static_shape(node.out_shapes[
                0]):
S
SunAhong1993 已提交
976 977 978 979 980
            self.paddle_graph.add_layer(
                'paddle.reshape',
                inputs={'x': val_x.name},
                outputs=[node.name],
                shape=node.out_shapes[0])
981
        else:
982 983
            # shape may be [], come form Gather by scalar indices
            if len(val_shape.out_shapes[0]) > 0:
S
SunAhong1993 已提交
984 985 986 987 988 989 990 991 992 993
                self.paddle_graph.add_layer(
                    'paddle.reshape',
                    inputs={'x': val_shape.name},
                    outputs=[val_shape.name],
                    shape=val_shape.out_shapes[0])
            self.paddle_graph.add_layer(
                'paddle.reshape',
                inputs={'x': val_x.name,
                        'shape': val_shape.name},
                outputs=node)
994 995

    @print_mapping_info
C
update  
channingss 已提交
996
    def Cast(self, node):
C
channingss 已提交
997
        val_input = self.graph.get_input_node(node, idx=0, copy=True)
C
update  
channingss 已提交
998 999 1000 1001 1002 1003 1004 1005 1006
        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'
S
SunAhong1993 已提交
1007 1008 1009 1010 1011
        self.paddle_graph.add_layer(
            'paddle.cast', 
            inputs={'x': val_input.name}, 
            outputs=[node.name], 
            dtype=string(dtype))
C
update  
channingss 已提交
1012

C
Channingss 已提交
1013 1014 1015
    @print_mapping_info
    def Not(self, node):
        val_input = self.graph.get_input_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
1016 1017 1018
        self.paddle_graph.add_layer('paddle.logical_not', 
                                    inputs={'x': val_input.name}, 
                                    outputs=[node.name])
C
Channingss 已提交
1019

1020
    @print_mapping_info
C
update  
channingss 已提交
1021
    def AveragePool(self, node):
C
channingss 已提交
1022
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
C
channingss 已提交
1023 1024

        auto_pad = node.get_attr('auto_pad', 'NOTSET')
C
update  
channingss 已提交
1025 1026 1027 1028 1029 1030
        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))
C
channingss 已提交
1031

C
channingss 已提交
1032 1033
        paddings, val_x = self._pad_if_asymmetric(node, pads, val_x)

C
channingss 已提交
1034
        if auto_pad == "SAME_UPPER" or auto_pad == "SAME_LOWER":
C
channingss 已提交
1035
            input_shape = val_x.out_shapes[0]
C
Channingss 已提交
1036 1037 1038 1039 1040
            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
C
channingss 已提交
1041

S
SunAhong1993 已提交
1042 1043
        paddle_op = 'paddle.nn.functional.avg_pool{}d'.format(poolnd)
        assert 1 <= poolnd <= 3, 'only avg_pool1d, avg_pool2d and avg_pool3d are supported'
S
SunAhong1993 已提交
1044
        layer_attrs = {
S
SunAhong1993 已提交
1045 1046 1047
            "kernel_size": kernel_shape,
            "stride": strides,
            "padding": paddings,
C
update  
channingss 已提交
1048
            "ceil_mode": ceil_mode,
S
SunAhong1993 已提交
1049
            "exclusive": True,
S
SunAhong1993 已提交
1050
            "name": string(node.name)
C
update  
channingss 已提交
1051
        }
S
SunAhong1993 已提交
1052 1053
        self.paddle_graph.add_layer(
            paddle_op, 
S
SunAhong1993 已提交
1054
            inputs={'x': val_x if isinstance(val_x, str) else val_x.name}, 
S
SunAhong1993 已提交
1055 1056
            outputs=[node.name], 
            **layer_attrs)
C
update  
channingss 已提交
1057

1058
    @print_mapping_info
C
update  
channingss 已提交
1059
    def Concat(self, node):
S
SunAhong1993 已提交
1060
        inputs_list = []
C
Channingss 已提交
1061
        dtypes = set()
C
update  
channingss 已提交
1062
        for i in range(len(node.layer.input)):
C
channingss 已提交
1063
            ipt = self.graph.get_input_node(node, idx=i, copy=True)
S
SunAhong1993 已提交
1064 1065
            inputs_list.append(ipt.name)
            dtypes.add(ipt.dtype)
C
Channingss 已提交
1066 1067
        if len(dtypes) > 1:
            assert 'Unspported situation happened, please create issue on https://github.com/PaddlePaddle/X2Paddle/issues.'
C
update  
channingss 已提交
1068
        axis = node.get_attr('axis')
S
SunAhong1993 已提交
1069 1070 1071 1072 1073
        self.paddle_graph.add_layer(
            'paddle.concat', 
            inputs={"x": inputs_list}, 
            outputs=[node.name], 
            axis=axis)
C
update  
channingss 已提交
1074

1075
    @print_mapping_info
C
update  
channingss 已提交
1076
    def Flatten(self, node):
C
channingss 已提交
1077
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
1078
        output_shape = node.out_shapes[0]
C
update  
channingss 已提交
1079
        axis = node.get_attr('axis', 1)
S
SunAhong1993 已提交
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
        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', 
            inputs={"x": val_x.name}, 
            outputs=[node.name],
            shape=shape_list)
C
update  
channingss 已提交
1094

1095
    @print_mapping_info
C
update  
channingss 已提交
1096
    def Gemm(self, node):
C
channingss 已提交
1097 1098 1099
        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)
C
update  
channingss 已提交
1100 1101 1102 1103 1104

        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 已提交
1105 1106 1107
        val_mm = node.name + '_mm'
        matmul_inputs = {"x": val_a.name, 
                         "y": val_b.name}
C
update  
channingss 已提交
1108 1109 1110 1111
        attr_matmul = {
            "transpose_x": trans_a,
            "transpose_y": trans_b,
        }
S
SunAhong1993 已提交
1112 1113
        self.paddle_graph.add_layer(
            'paddle.matmul',
1114
            inputs=matmul_inputs,
S
SunAhong1993 已提交
1115 1116 1117 1118 1119 1120 1121
            outputs=[val_mm],
            **attr_matmul)
        self.paddle_graph.add_layer(
            "paddle.scale", 
            inputs={"x": val_mm}, 
            outputs=[val_mm],
            scale=alpha)
C
channingss 已提交
1122

C
update  
channingss 已提交
1123 1124
        if beta != 0:
            if beta == 1.:
S
SunAhong1993 已提交
1125 1126 1127 1128
                add_inputs = {"x": val_mm, 
                              "y": val_c.name}
                self.paddle_graph.add_layer(
                    "paddle.add",
1129
                    inputs=add_inputs,
S
SunAhong1993 已提交
1130
                    outputs=[node.name])
C
update  
channingss 已提交
1131
            else:
S
SunAhong1993 已提交
1132 1133 1134 1135 1136 1137
                var_beta = node.name + '_beta'
                self.paddle_graph.add_layer(
                    "paddle.scale",
                    inputs={"x": val_c.name},
                    outputs=[var_beta],
                    scale=beta)
C
channingss 已提交
1138
                add_inputs = {"x": val_mm, "y": var_beta}
S
SunAhong1993 已提交
1139 1140
                self.paddle_graph.add_layer(
                    "paddle.add",
1141
                    inputs=add_inputs,
S
SunAhong1993 已提交
1142
                    outputs=[node.name])
C
update  
channingss 已提交
1143

1144
    @print_mapping_info
C
update  
channingss 已提交
1145
    def Sum(self, node):
1146
        val_inps = node.layer.input
S
SunAhong1993 已提交
1147
        inputs_dict = {
1148
            "x": self.graph.get_input_node(
S
SunAhong1993 已提交
1149
                node, idx=0, copy=True).name,
1150
            "y": self.graph.get_input_node(
S
SunAhong1993 已提交
1151
                node, idx=1, copy=True).name,
1152
        }
S
SunAhong1993 已提交
1153 1154 1155
        self.paddle_graph.add_layer("paddle.add", 
                                    inputs=inputs_dict, 
                                    outputs=[node.name])
1156

C
channingss 已提交
1157 1158
        for idx, ipt in enumerate(val_inps[2:]):
            y = self.graph.get_input_node(node, idx=idx, copy=True)
S
SunAhong1993 已提交
1159 1160 1161
            inputs_dict = {
                "x": node.name,
                "y": y.name,
1162
            }
S
SunAhong1993 已提交
1163 1164 1165 1166
            self.paddle_graph.add_layer(
                "paddle.add", 
                inputs=inputs_dict, 
                outputs=[node.name])
C
update  
channingss 已提交
1167

1168
    @print_mapping_info
C
update  
channingss 已提交
1169
    def MatMul(self, node):
C
channingss 已提交
1170 1171
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_y = self.graph.get_input_node(node, idx=1, copy=True)
C
Channingss 已提交
1172 1173
        x_shape = val_x.out_shapes[0]
        y_shape = val_y.out_shapes[0]
S
SunAhong1993 已提交
1174 1175
        inputs_dict = {"x": val_x.name, 
                       "y": val_y.name}
C
Channingss 已提交
1176
        if y_shape[0] == 1 and x_shape[-1] != 1 and x_shape[0] != 1:
S
SunAhong1993 已提交
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
            y_squeeze = val_y.name + '_squeeze'
            self.paddle_graph.add_layer(
                "paddle.squeeze",
                inputs={"x": val_y.name},
                outputs=[y_squeeze],
                axis=[0])
            inputs_dict['y'] = y_squeeze
            self.paddle_graph.add_layer(
                "paddle.matmul", 
                inputs=inputs_dict, 
                outputs=[node.name])
C
Channingss 已提交
1188
        else:
S
SunAhong1993 已提交
1189 1190 1191 1192 1193
            self.paddle_graph.add_layer(
                "paddle.matmul", 
                inputs=inputs_dict, 
                outputs=[node.name])
            
1194
    @print_mapping_info
C
update  
channingss 已提交
1195
    def BatchNormalization(self, node):
C
channingss 已提交
1196 1197 1198 1199 1200
        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)
C
update  
channingss 已提交
1201 1202 1203 1204

        momentum = node.get_attr('momentum', .9)
        epsilon = node.get_attr('epsilon', 1e-5)

C
channingss 已提交
1205 1206
        # Attribute: spatial is used in BatchNormalization-1,6,7
        spatial = bool(node.get_attr('spatial'))
S
SunAhong1993 已提交
1207
        layer_attrs = {
C
update  
channingss 已提交
1208 1209 1210
            "momentum": momentum,
            "epsilon": epsilon,
        }
S
SunAhong1993 已提交
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
        self.paddle_graph.add_layer(
            "paddle.nn.functional.batch_norm", 
            inputs={"x": val_x.name,
                    "weight": val_scale.name,
                    "bias": val_b.name,
                    "running_mean": val_mean.name,
                    "running_var": val_var.name}, 
            outputs=[node.name], 
            **layer_attrs)
        
1221
    @print_mapping_info
C
update  
channingss 已提交
1222
    def Transpose(self, node):
C
channingss 已提交
1223
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
C
update  
channingss 已提交
1224
        perm = node.get_attr('perm')
S
SunAhong1993 已提交
1225 1226 1227 1228 1229
        self.paddle_graph.add_layer(
            "paddle.transpose", 
            inputs={"x": val_x.name},
            outputs=[node.name], 
            perm=perm)
C
update  
channingss 已提交
1230

1231
    @print_mapping_info
C
update  
channingss 已提交
1232
    def PRelu(self, node):
S
SunAhong1993 已提交
1233 1234 1235
        op_name = name_generator("prelu", self.nn_name2id)
        output_name = node.name
        layer_outputs = [op_name, output_name]
C
channingss 已提交
1236 1237
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_slope = self.graph.get_input_node(node, idx=1, copy=True)
C
update  
channingss 已提交
1238

C
channingss 已提交
1239 1240
        mode = 'channel'
        shape_slope = val_slope.out_shapes[0]
C
Channingss 已提交
1241
        if shape_slope == [1]:
C
channingss 已提交
1242 1243
            mode = 'all'
        elif len(shape_slope) > 2:
S
SunAhong1993 已提交
1244
            raise Exception("The 'element' mode is not supported yet!")
C
Channingss 已提交
1245 1246 1247 1248 1249

        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 已提交
1250 1251 1252 1253 1254 1255 1256
            self.params[val_slope.name] = slope_data
  
        self.paddle_graph.add_layer(
            "paddle.nn.functional.prelu", 
            inputs={"x": val_x.name,
                    "weight": val_slope.name}, 
            outputs=[node.name])
C
update  
channingss 已提交
1257

1258
    @print_mapping_info
C
update  
channingss 已提交
1259
    def Squeeze(self, node):
C
channingss 已提交
1260 1261
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        axes = node.get_attr('axes')
1262
        if len(val_x.out_shapes[0]) == 1:
S
SunAhong1993 已提交
1263 1264 1265 1266 1267
            self.paddle_graph.add_layer(
                "paddle.cast",
                inputs={"x": val_x.name},
                outputs=[node.name],
                dtype=string(val_x.dtype))
1268
        else:
S
SunAhong1993 已提交
1269 1270 1271 1272 1273
            self.paddle_graph.add_layer(
                "paddle.squeeze", 
                inputs={"x": val_x.name}, 
                outputs=[node.name], 
                axis=axes)
R
root 已提交
1274

1275
    @print_mapping_info
C
channings 已提交
1276 1277 1278
    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)
S
SunAhong1993 已提交
1279 1280 1281 1282 1283
        self.paddle_graph.add_layer(
            "paddle.equal",
            inputs={'x': val_x.name,
                    'y': val_y.name},
            outputs=[node.name])
1284

C
Channingss 已提交
1285 1286 1287 1288
    @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)
S
SunAhong1993 已提交
1289 1290 1291 1292 1293
        self.paddle_graph.add_layer(
            "paddle.greater_than",
            inputs={'x': val_x.name,
                    'y': val_y.name},
            outputs=node,
C
Channingss 已提交
1294 1295
            param_attr=None)

1296
    @print_mapping_info
C
channings 已提交
1297 1298 1299 1300
    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)
R
root 已提交
1301

S
SunAhong1993 已提交
1302 1303 1304 1305 1306
        not_condition = condition.name + '_not'
        self.paddle_graph.add_layer(
            "paddle.logical_not",
            inputs={"x": condition.name},
            outputs=[not_condition])
R
root 已提交
1307
        cast_not_condition = not_condition + '_cast'
S
SunAhong1993 已提交
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
        self.paddle_graph.add_layer(
            "paddle.cast",
            inputs={"x": not_condition},
            outputs=[cast_not_condition],
            dtype=string(val_x.dtype))
        cast_condition = condition.name + '_cast'
        self.paddle_graph.add_layer(
            "paddle.cast",
            inputs={"x": condition.name},
            outputs=[cast_condition],
            dtype=string(val_x.dtype))
        mul_val_x = val_x.name + '_mul'
        self.paddle_graph.add_layer(
            "paddle.multiply",
            inputs={'x': val_x.name,
1323
                    'y': cast_condition},
S
SunAhong1993 已提交
1324 1325 1326 1327 1328
            outputs=[mul_val_x])
        mul_val_y = val_y.name + '_mul'
        self.paddle_graph.add_layer(
            "paddle.multiply",
            inputs={'x': val_y.name,
1329
                    'y': cast_not_condition},
S
SunAhong1993 已提交
1330
            outputs=[mul_val_y])
1331

S
SunAhong1993 已提交
1332 1333
        self.paddle_graph.add_layer(
            "paddle.add",
1334 1335
            inputs={'x': mul_val_x,
                    'y': mul_val_y},
S
SunAhong1993 已提交
1336
            outputs=[node.name])
1337 1338

    @print_mapping_info
R
root 已提交
1339 1340
    def NonZero(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
1341 1342
        val_x_dim = len(val_x.out_shapes[0])
        if val_x_dim == 1:
S
SunAhong1993 已提交
1343 1344 1345 1346 1347 1348 1349 1350 1351
            self.paddle_graph.add_layer(
                "paddle.nonzero", 
                inputs={"x": val_x.name}, 
                outputs=[val_x.name])
            self.paddle_graph.add_layer(
                "paddle.transpose",
                inputs={"x": val_x.name},
                outputs=[node.layer_naem],
                perm=[1, 0])
1352
        if val_x_dim > 1:
S
SunAhong1993 已提交
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
            self.paddle_graph.add_layer(
                "paddle.nonzero", 
                inputs={"x": val_x.name}, 
                outputs=[val_x.name])
            self.paddle_graph.add_layer(
                "paddle.split",
                inputs={"x": val_x.name}, 
                outputs=[val_x.name],
                num_or_sections=1,
                axis=val_x_dim)
            self.paddle_graph.add_layer(
                "paddle.concat", 
                inputs={"x": val_x.name}, 
                outputs=[node.name])
1367 1368

    @print_mapping_info
C
update  
channingss 已提交
1369
    def Identity(self, node):
C
channingss 已提交
1370
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
1371 1372 1373 1374 1375
        self.paddle_graph.add_layer(
            "paddle.assign", 
            inputs={"x": val_x.name}, 
            outputs=[node.name])
        
1376
    @print_mapping_info
C
channings 已提交
1377 1378 1379 1380
    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)
R
root 已提交
1381

1382
        if repeats is None:
S
SunAhong1993 已提交
1383
            repeats = val_repeats.name
J
jiangjiajun 已提交
1384
            if val_repeats.dtype != 'int32':
S
SunAhong1993 已提交
1385 1386 1387 1388 1389
                self.paddle_graph.add_layer(
                    "paddle.cast",
                    inputs={"x": repeats},
                    outputs=["{}.tmp".format(repeats)],
                    dtype=string("int32"))
J
jiangjiajun 已提交
1390 1391
                repeats = "{}.tmp".format(repeats)

1392
        elif isinstance(repeats, int):
C
channings 已提交
1393
            repeats = [repeats]
R
root 已提交
1394

C
channings 已提交
1395
        attr = {
R
root 已提交
1396
            'expand_times': repeats,
S
SunAhong1993 已提交
1397
            "name": string(node.name),
C
channings 已提交
1398
        }
S
SunAhong1993 已提交
1399 1400 1401 1402 1403
        self.paddle_graph.add_layer(
            "paddle.tile", 
            inputs={"x": val_x.name}, 
                    outputs=[node.name], 
                    repeat_times=repeats)
R
root 已提交
1404

1405
    @print_mapping_info
C
update  
channingss 已提交
1406
    def MaxPool(self, node):
C
channingss 已提交
1407
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
C
channingss 已提交
1408
        auto_pad = node.get_attr('auto_pad', 'NOTSET')
C
update  
channingss 已提交
1409 1410 1411 1412 1413 1414 1415 1416 1417
        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
S
SunAhong1993 已提交
1418 1419
        paddle_op = 'paddle.nn.functional.max_pool{}d'.format(poolnd)
        assert 1 <= poolnd <= 3, 'only max_pool1d, max_pool2d and max_pool3d are supported'
C
channingss 已提交
1420

C
channingss 已提交
1421 1422
        paddings, val_x = self._pad_if_asymmetric(node, pads, val_x)

C
channingss 已提交
1423
        if auto_pad == "SAME_UPPER" or auto_pad == "SAME_LOWER":
C
channingss 已提交
1424
            input_shape = val_x.out_shapes[0]
C
Channingss 已提交
1425 1426 1427 1428 1429
            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
S
SunAhong1993 已提交
1430 1431 1432 1433 1434
            
        layer_attrs = {
            "kernel_size": kernel_shape,
            "stride": strides,
            "padding": paddings,
C
update  
channingss 已提交
1435 1436
            "ceil_mode": ceil_mode,
        }
S
SunAhong1993 已提交
1437 1438 1439 1440 1441
        self.paddle_graph.add_layer(
            paddle_op, 
            inputs={'x': val_x if isinstance(val_x, str) else val_x.name}, 
            outputs=[node.name], 
            **layer_attrs)
R
root 已提交
1442

1443
    @print_mapping_info
C
channings 已提交
1444
    def GlobalMaxPool(self, node):
S
SunAhong1993 已提交
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
        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.functional.adaptive_max_pool{}d'.format(poolnd)
        assert 1 <= poolnd <= 3, 'only adaptive_max_pool1d, adaptive_max_pool2d and adaptive_max_pool3d are supported'
        output_shape = node.out_shapes[0]
        self.paddle_graph.add_layer(
            paddle_op, 
            inputs={'x': val_x.name}, 
            outputs=[node.name], 
            output_size=output_shape[2:])
        
1462
    @print_mapping_info
C
channings 已提交
1463
    def GlobalAveragePool(self, node):
S
SunAhong1993 已提交
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
        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.functional.adaptive_avg_pool{}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, 
            inputs={'x': val_x.name}, 
            outputs=[node.name], 
            output_size=output_shape[2:])
R
root 已提交
1480

1481
    @print_mapping_info
C
update  
channingss 已提交
1482
    def Conv(self, node):
C
channingss 已提交
1483 1484
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_w = self.graph.get_input_node(node, idx=1, copy=True)
C
update  
channingss 已提交
1485 1486
        has_bias = len(node.layer.input) == 3
        if has_bias:
C
channingss 已提交
1487
            val_b = self.graph.get_input_node(node, idx=2, copy=True)
C
update  
channingss 已提交
1488 1489
        auto_pad = node.get_attr('auto_pad', 'NOTSET')

C
channingss 已提交
1490
        kernel_shape = node.get_attr('kernel_shape')
C
update  
channingss 已提交
1491 1492
        convnd = len(kernel_shape)
        assert 2 <= convnd <= 3, 'only conv2d and conv3d is supported'
C
Channingss 已提交
1493
        num_out_channels = val_w.out_shapes[0][0]
S
SunAhong1993 已提交
1494 1495
        num_in_channels = val_w.out_shapes[0][1]
        paddle_op = 'paddle.nn.functional.conv{}d'.format(convnd)
C
update  
channingss 已提交
1496 1497

        num_groups = node.get_attr('group', 1)
C
Channingss 已提交
1498 1499 1500
        strides = node.get_attr('strides', [1] * convnd)
        dilations = node.get_attr('dilations', [1] * convnd)
        pads = node.get_attr('pads', [0] * (convnd * 2))
C
update  
channingss 已提交
1501

C
channingss 已提交
1502
        input_shape = val_x.out_shapes[0]
C
update  
channingss 已提交
1503 1504
        paddings, val_x = self._pad_if_asymmetric(node, pads, val_x)

C
channingss 已提交
1505
        if auto_pad == "SAME_UPPER" or auto_pad == "SAME_LOWER":
C
Channingss 已提交
1506 1507 1508 1509 1510
            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
C
update  
channingss 已提交
1511

S
SunAhong1993 已提交
1512
        layer_attrs = {
C
update  
channingss 已提交
1513 1514 1515 1516
            "stride": strides,
            "padding": paddings,
            "dilation": dilations,
            "groups": num_groups,
S
SunAhong1993 已提交
1517 1518 1519 1520
        }
        layer_inputs = {
            "x": val_x.name,
            "weight": val_w.name
C
update  
channingss 已提交
1521 1522
        }
        if has_bias:
S
SunAhong1993 已提交
1523 1524 1525 1526 1527 1528
            layer_inputs["bias"] = val_b.name
        self.paddle_graph.add_layer(
            paddle_op, 
            inputs=layer_inputs, 
            outputs=[node.name], 
            **layer_attrs)
C
channingss 已提交
1529

1530
    @print_mapping_info
C
channingss 已提交
1531
    def ConvTranspose(self, node):
C
channingss 已提交
1532 1533
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_w = self.graph.get_input_node(node, idx=1, copy=True)
C
channingss 已提交
1534
        val_b = None
R
root 已提交
1535
        if len(node.layer.input) > 2:
C
channingss 已提交
1536
            val_b = self.graph.get_input_node(node, idx=2, copy=True)
C
channingss 已提交
1537 1538
        auto_pad = node.get_attr('auto_pad', 'NOTSET')
        out_padding = node.get_attr('output_padding', [0, 0])
C
channingss 已提交
1539
        kernel_shape = node.get_attr('kernel_shape')
C
channingss 已提交
1540 1541 1542
        assert kernel_shape, 'kernel_shape not inferred'
        convnd = len(kernel_shape)
        assert 2 <= convnd <= 3, 'only conv2d_transpose and conv3d_transpose supported'
S
SunAhong1993 已提交
1543
        num_in_channels = val_w.out_shapes[0][0]
C
channingss 已提交
1544
        num_out_channels = val_w.out_shapes[0][1]
S
SunAhong1993 已提交
1545
        paddle_op = 'paddle.nn.functional.conv{}d_transpose'.format(convnd)
C
channingss 已提交
1546

C
channingss 已提交
1547 1548 1549 1550 1551
        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))
C
channingss 已提交
1552 1553 1554 1555

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

        output_size = [0, 0]
C
channingss 已提交
1556

1557 1558
        output_size[0] = (val_x.out_shapes[0][2] - 1
                          ) * strides[0] - 2 * paddings[0] + dilations[0] * (
C
channingss 已提交
1559
                              kernel_shape[0] - 1) + 1 + out_padding[0]
1560 1561
        output_size[1] = (val_x.out_shapes[0][3] - 1
                          ) * strides[1] - 2 * paddings[1] + dilations[1] * (
C
channingss 已提交
1562
                              kernel_shape[1] - 1) + 1 + out_padding[1]
S
SunAhong1993 已提交
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
        layer_inputs = {'x': val_x.name,
                       "weight": val_w.name}
        layer_attrs = {
            "stride": strides,
            "dilation": dilations,
            "padding": paddings,
            "groups": num_groups,
            "output_size": node.out_shapes[0][2:]}
        if val_b is not None:
            layer_inputs["bias"] = val_b.name
        self.paddle_graph.add_layer(
S
fix  
SunAhong1993 已提交
1574
            kernel=paddle_op,
S
SunAhong1993 已提交
1575 1576
            inputs=layer_inputs,
            outputs=[node.name],
S
fix  
SunAhong1993 已提交
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
            **layer_attrs)
        
    @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],
S
SunAhong1993 已提交
1590
            **layer_attrs)