onnx_op_mapper.py 42.1 KB
Newer Older
C
update  
channingss 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#   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.core.graph import GraphNode
from x2paddle.core.op_mapper import OpMapper
from x2paddle.core.fluid_code import Layer
from x2paddle.core.fluid_code import FluidCode
from x2paddle.decoder.onnx_decoder import ONNXGraph, ONNXGraphNode, ONNXGraphDataNode
from x2paddle.op_mapper.onnx_directly_map import default_op_mapping_field_values
from x2paddle.op_mapper.onnx_directly_map import default_op_mapping
from x2paddle.op_mapper.onnx_directly_map import default_ioa_constraint
C
channingss 已提交
23
from x2paddle.op_mapper.onnx_custom_layer import *
C
channingss 已提交
24
from x2paddle.core.util import string
C
update  
channingss 已提交
25
import numpy as np
C
channingss 已提交
26
import onnx.numpy_helper as numpy_helper
C
channingss 已提交
27
from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE
C
update  
channingss 已提交
28 29
import logging as _logging
from collections import OrderedDict as _dict
C
channingss 已提交
30
import math
C
update  
channingss 已提交
31 32 33 34 35 36

_logger = _logging.getLogger(__name__)


def _const_weight_or_none(node):
    if 'Constant' in node.layer_name:
C
channingss 已提交
37
        return node.value
C
update  
channingss 已提交
38 39 40 41 42
    if isinstance(node, ONNXGraphDataNode):
        return node.weight
    return None


C
channingss 已提交
43 44 45 46 47 48 49 50
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]


C
update  
channingss 已提交
51 52 53 54 55 56 57 58
class ONNXOpMapper(OpMapper):
    def __init__(self, decoder):
        super(ONNXOpMapper, self).__init__()
        self.decoder = decoder
        self.graph = decoder.onnx_graph
        self.input_shapes = []
        self.weights = dict()
        self.omit_nodes = list()
C
channingss 已提交
59
        self.used_custom_layers = dict()
C
update  
channingss 已提交
60 61 62 63 64

        if not self.op_checker():
            raise Exception("Model are not supported yet.")

        #mapping op
C
updatea  
channingss 已提交
65 66 67 68 69
        print("Total nodes: {}".format(
            sum([
                isinstance(node, ONNXGraphNode)
                for name, node in self.graph.node_map.items()
            ])))
C
update  
channingss 已提交
70 71 72 73 74 75 76
        for node_name in self.graph.topo_sort:
            node = self.graph.get_node(node_name)
            op = node.layer_type
            if hasattr(self, op):
                func = getattr(self, op)
                func(node)
            elif op in default_op_mapping:
C
channingss 已提交
77
                self.directly_map(node)
C
channingss 已提交
78 79
            elif op in custom_layers:
                self.deal_custom_layer(node)
C
update  
channingss 已提交
80 81 82 83 84 85

    def op_checker(self):
        unsupported_ops = set()
        for node_name in self.graph.topo_sort:
            node = self.graph.get_node(node_name)
            op = node.layer_type
C
channingss 已提交
86 87 88
            if not hasattr(
                    self, op
            ) and op not in default_op_mapping and op not in custom_layers:
C
update  
channingss 已提交
89 90 91 92 93 94 95 96 97 98
                unsupported_ops.add(op)
        if len(unsupported_ops) == 0:
            return True
        else:
            print("There are {} ops not supported yet, list as below".format(
                len(unsupported_ops)))
            for op in unsupported_ops:
                print(op)
            return False

C
channingss 已提交
99
    def directly_map(self, node, name='', *args, **kwargs):
C
update  
channingss 已提交
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
        inputs = node.layer.input
        outputs = node.layer.output
        op_type = node.layer_type
        attrs = node.attr_map

        info = default_op_mapping[op_type]
        info.extend(list(default_op_mapping_field_values.values())[len(info):])
        (
            fluid_op,
            fluid_input_args,
            fluid_output_args,
            attr_mapping,
            default_attrs,
            input_perm,
            output_perm,
            fill_name_field,
        ) = info

        if fluid_op in default_ioa_constraint:
            for predicate, message in default_ioa_constraint[fluid_op]:
                assert predicate(inputs, outputs, attrs), message

        mapped_attrs = {
            attr_mapping.get(key, key): value
            for key, value in attrs.items()
        }
        if '' in mapped_attrs:
            mapped_attrs.pop('')
        if '_' in mapped_attrs:
            mapped_attrs.pop('_')
        fluid_attrs = default_attrs.copy()
        fluid_attrs.update(mapped_attrs)
C
channingss 已提交
132
        inputs = inputs if input_perm is None else list(
C
update  
channingss 已提交
133
            map(lambda i: inputs[i], input_perm))
C
channingss 已提交
134 135 136 137
        val_inps = []
        for idx, ipt in enumerate(inputs):
            val_inps.append(self.graph.get_input_node(node, idx=idx, copy=True))

C
update  
channingss 已提交
138 139 140 141 142 143
        val_outs = outputs if output_perm is None else list(
            map(lambda i: outputs[i], output_perm))
        attr = fluid_attrs
        if fluid_op not in ['shape', 'gather']:
            attr['name'] = string(node.layer_name)
        node.fluid_code.add_layer(fluid_op,
C
channingss 已提交
144
                                  inputs=val_inps,
C
update  
channingss 已提交
145 146 147
                                  output=val_outs[0],
                                  param_attr=attr)

C
channingss 已提交
148 149 150
    def deal_custom_layer(self, node):
        op = node.layer_type
        custom_code, func = make_custom_layer(node)
C
channingss 已提交
151
        child_func_code, child_func = make_custom_child_func(node)
C
channingss 已提交
152 153 154 155
        params = get_params(node.layer, node.layer_type)
        arg_names, kwargs = set_args(func, params)
        kwargs['name'] = string(node.layer_name)
        node.fluid_code.add_layer(func.__code__.co_name,
C
channingss 已提交
156
                                  inputs=node.inputs,
C
channingss 已提交
157 158 159 160 161
                                  output=node,
                                  param_attr=kwargs,
                                  is_custom_layer=True)
        if op not in self.used_custom_layers:
            self.used_custom_layers[op] = custom_code
C
channingss 已提交
162 163
            if op + '_child_func' not in self.used_custom_layers:
                self.used_custom_layers[op + '_child_func'] = child_func_code
C
channingss 已提交
164

C
update  
channingss 已提交
165
    def place_holder(self, node):
C
channingss 已提交
166
        self.input_shapes.append(node.out_shapes[0])
C
update  
channingss 已提交
167 168
        attr = {
            "dtype": string(node.dtype),
C
channingss 已提交
169
            "shape": node.out_shapes[0],
C
update  
channingss 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182
            "name": string(node.layer_name),
            "append_batch_size": 'False'
        }

        node.fluid_code.add_layer("data",
                                  inputs=None,
                                  output=node,
                                  param_attr=attr)

    def create_parameter(self, node, parameter=None):
        if parameter is not None:
            node = parameter
        dtype = node.dtype
C
channingss 已提交
183
        shape = node.out_shapes[0]
C
update  
channingss 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210

        self.weights[node.layer_name] = node.weight
        attr = {
            'dtype': string(dtype),
            'shape': shape,
            'name': string(node.layer_name),
            'attr': string(node.layer_name),
            'default_initializer': 'Constant(0.0)'
        }
        node.fluid_code.add_layer("create_parameter",
                                  inputs=None,
                                  output=node,
                                  param_attr=attr)

    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 已提交
211
    def _interpolate(self, node):
C
channingss 已提交
212 213
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_scales = self.graph.get_input_node(node, idx=1, copy=True)
C
channingss 已提交
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
        val_y = self.graph.get_node(node.layer.output[0], copy=True)

        out_shape_ = val_y.out_shapes[0]
        if out_shape_ is not None:
            assert len(out_shape_) == 4, 'only 4-D Tensor as X and Y supported'
            out_shape_ = out_shape_[2:]
        scales = _const_weight_or_none(val_scales)
        if scales is not None:
            assert len(scales) == 4, 'only 4-D Tensor as X and Y supported'
            assert scales[0] == 1 and scales[
                1] == 1, 'only scale on (NC)HW supported'
            assert scales[2] == scales[
                3], 'only aspect-ratio-invariant scale supported'
        scale = scales[2] if scales else None
        if scale is None:
            assert out_shape_, 'neither scales nor output shape is available'
            out_shape = out_shape_
        else:
            out_shape = None
            if out_shape_ is None:
                in_shape = val_x.out_shapes[0]
                assert in_shape is not None, 'out_shape required but not inferrable'
                assert len(
                    in_shape) == 4, 'only 4-D Tensor as X and Y supported'
                out_shape_ = [in_shape[2] * scale, in_shape[3] * scale]

        mode = node.get_attr('mode', 'nearest')
        fluid_op = 'resize_{}'.format(mode)

        attr = {
            'scale': scale,
            'out_shape': out_shape,
            'name': string(node.layer_name)
        }
        node.fluid_code.add_layer(fluid_op,
                                  inputs=val_x,
                                  output=node,
                                  param_attr=attr)

C
update  
channingss 已提交
253
    def Pad(self, node, op_independent=True):
C
channingss 已提交
254
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
C
update  
channingss 已提交
255 256 257
        pads = node.get_attr('pads')
        mode = node.get_attr('mode', 'constant')
        value = node.get_attr('value', 0.)
C
channingss 已提交
258 259
        data_shape = val_x.out_shapes[0]
        output_shape = node.out_shapes[0]
C
update  
channingss 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
        assume_pad2d = False
        attr = {}
        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:
            fluid_op = 'pad2d'
            attr['data_format'] = string('NCHW')
            attr['mode'] = string(mode)
        else:
            attr = {'pad_value': value}
            fluid_op = 'pad'
        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 已提交
281 282 283 284
            if sum(paddings[:4]) == 0:
                fluid_op = 'pad2d'
                paddings = paddings[4:]
                attr['mode'] = string(mode)
C
update  
channingss 已提交
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
        attr['paddings'] = paddings
        if op_independent:
            attr['name'] = string(node.layer_name)
            node.fluid_code.add_layer(fluid_op,
                                      inputs=val_x,
                                      output=node,
                                      param_attr=attr)
        else:
            attr['name'] = string(node.layer_name + '_paded')
            node.fluid_code.add_layer(fluid_op,
                                      inputs=val_x,
                                      output=node.layer_name + '_paded',
                                      param_attr=attr)
            return node.layer_name + '_paded'

C
channingss 已提交
300 301 302 303 304 305 306 307 308 309
    def TopK(self, node):
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        axes = node.get_attr('axes')
        k = 10
        attr = {'k': k, 'name': string(node.layer_name)}
        node.fluid_code.add_layer('topk',
                                  inputs=val_x,
                                  output=node,
                                  param_attr=attr)

C
update  
channingss 已提交
310
    def Unsqueeze(self, node):
C
channingss 已提交
311
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
C
update  
channingss 已提交
312 313 314 315 316 317 318
        axes = node.get_attr('axes')
        attr = {'axes': axes, 'name': string(node.layer_name)}
        node.fluid_code.add_layer('unsqueeze',
                                  inputs=val_x,
                                  output=node,
                                  param_attr=attr)

C
channingss 已提交
319
    def Shrink(self, node):
C
channingss 已提交
320
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
C
channingss 已提交
321 322 323 324 325 326 327 328 329
        bias = node.get_attr('bias')
        lambd = node.get_attr('lambd')
        assert bias == 0.0, 'not support bias!=0'
        attr = {'threshold': lambd, 'name': node.layer_name}
        node.fluid_code.add_layer('hard_shrink',
                                  inputs=val_x,
                                  output=node,
                                  param_attr=attr)

C
update  
channingss 已提交
330 331 332 333 334 335 336 337 338 339 340
    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:
C
channingss 已提交
341
            shape = val_output.out_shapes[0]
C
update  
channingss 已提交
342 343 344 345 346 347 348 349 350
        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',
                val_output.layer_name, val_output.layer_name)

        if len(value) == 1:  # scalar
C
channingss 已提交
351
            value = value.tolist()
C
update  
channingss 已提交
352 353 354 355 356 357 358 359 360
            shape = [1]
            value = value[0]
            if dtype.name == 'int64':
                dtype = 'int32'
            attr = {'shape': shape, 'dtype': string(dtype), 'value': value}
            node.fluid_code.add_layer('fill_constant',
                                      inputs=None,
                                      output=node,
                                      param_attr=attr)
C
channingss 已提交
361 362 363 364 365 366 367 368 369 370 371 372 373 374
        else:
            value = np.reshape(value, shape)
            self.weights[node.layer_name] = value
            attr = {
                'dtype': string(dtype),
                'shape': shape,
                'name': string(node.layer_name),
                'attr': string(node.layer_name),
                'default_initializer': 'Constant(0.0)'
            }
            node.fluid_code.add_layer("create_parameter",
                                      inputs=None,
                                      output=node,
                                      param_attr=attr)
C
update  
channingss 已提交
375 376

    def Resize(self, node):
C
channingss 已提交
377 378
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_scales = self.graph.get_input_node(node, idx=1, copy=True)
C
channingss 已提交
379
        val_y = self.graph.get_node(node.layer.output[0], copy=True)
C
update  
channingss 已提交
380

C
channingss 已提交
381
        out_shape_ = val_y.out_shapes[0]
C
update  
channingss 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
        if out_shape_ is not None:
            assert len(out_shape_) == 4, 'only 4-D Tensor as X and Y supported'
            out_shape_ = out_shape_[2:]
        scales = _const_weight_or_none(val_scales)
        if scales is not None:
            assert len(scales) == 4, 'only 4-D Tensor as X and Y supported'
            assert scales[0] == 1 and scales[
                1] == 1, 'only scale on (NC)HW supported'
            assert scales[2] == scales[
                3], 'only aspect-ratio-invariant scale supported'
        scale = scales[2] if scales else None
        if scale is None:
            assert out_shape_, 'neither scales nor output shape is available'
            out_shape = out_shape_
        else:
            out_shape = None
            if out_shape_ is None:
C
channingss 已提交
399
                in_shape = val_x.out_shapes[0]
C
update  
channingss 已提交
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
                assert in_shape is not None, 'out_shape required but not inferrable'
                assert len(
                    in_shape) == 4, 'only 4-D Tensor as X and Y supported'
                out_shape_ = [in_shape[2] * scale, in_shape[3] * scale]

        mode = node.get_attr('mode', 'nearest')
        fluid_op = 'resize_{}'.format(mode)
        attr = {
            'scale': scale,
            'out_shape': out_shape,
            'name': string(node.layer_name)
        }
        node.fluid_code.add_layer(fluid_op,
                                  inputs=val_x,
                                  output=node,
                                  param_attr=attr)

C
channingss 已提交
417 418 419
    def Upsample(self, node):
        self._interpolate(node)

C
channingss 已提交
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
    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')
        print(indices.layer_name)
        print(indices_shape)
        assert len(
            indices_shape) == 1, "Gather op don't support dim of indice >1 "
        if axis == 0 and len(indices_shape) == 1:
            node.fluid_code.add_layer('gather',
                                      inputs=[val_x, indices],
                                      output=node,
                                      param_attr=None)
        elif axis > 0 and len(indices_shape) == 1:
            perm = [range(len(indices_shape))]
            perm = [axis] + perm[:axis] + perm[axis + 1:]
            attr_trans = {'perm': perm}
            name_trans = val_x.layer_name + '_trans'
            node.fluid_code.add_layer('transpose',
                                      inputs=val_x,
                                      output=name_trans,
                                      param_attr=attr_trans)
            node.fluid_code.add_layer('gather',
                                      inputs=[name_trans, indices],
                                      output=node,
                                      param_attr=None)
            node.fluid_code.add_layer('transpose',
                                      inputs=node,
                                      output=node,
                                      param_attr=attr_trans)

C
channingss 已提交
452
    def Slice(self, node):
C
channingss 已提交
453 454 455 456 457 458
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        val_starts = self.graph.get_input_node(node, idx=1, copy=True)
        val_ends = self.graph.get_input_node(node, idx=2, copy=True)
        val_axes = self.graph.get_input_node(node, idx=3, copy=True)
        val_steps = self.graph.get_input_node(node, idx=4, copy=True)

C
channingss 已提交
459 460
        val_y = self.graph.get_node(node.layer.output[0], copy=True)

C
channingss 已提交
461 462 463 464 465 466 467 468 469 470
        starts = _const_weight_or_none(val_starts).copy()
        ends = _const_weight_or_none(val_ends).copy()
        axes = _const_weight_or_none(val_axes)
        steps = _const_weight_or_none(val_steps)

        self.omit_nodes.append(val_starts.layer_name)
        self.omit_nodes.append(val_ends.layer_name)
        self.omit_nodes.append(val_axes.layer_name)
        self.omit_nodes.append(val_steps.layer_name)

C
channingss 已提交
471 472 473 474
        shape = val_x.out_shapes[0]

        if shape is not None:
            for idx, value in enumerate(starts):
C
channingss 已提交
475 476
                if value > shape[axes[idx]]:
                    starts[idx] = shape[axes[idx]]
C
channingss 已提交
477
            for idx, value in enumerate(ends):
C
channingss 已提交
478 479
                if value > shape[axes[idx]]:
                    ends[idx] = shape[axes[idx]]
C
channingss 已提交
480 481 482 483 484 485
        attr = {"axes": axes, "starts": starts, "ends": ends}
        node.fluid_code.add_layer('slice',
                                  inputs=val_x,
                                  output=node,
                                  param_attr=attr)

C
update  
channingss 已提交
486
    def ConstantOfShape(self, node):
C
channingss 已提交
487
        val_shape = self.graph.get_input_node(node, idx=0, copy=True)
C
channingss 已提交
488
        val_y = self.graph.get_node(node.layer.output[0], copy=True)
C
update  
channingss 已提交
489 490 491
        shape = _const_weight_or_none(val_shape)

        if shape is None:
C
channingss 已提交
492
            shape = node.out_shapes[0]
C
update  
channingss 已提交
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512

        assert shape is not None, (
            'given shape is neither const value nor deductible from output, '
            'this is not supported')

        value = node.get_attr('value')
        dtype = value.dtype
        value = value.tolist()
        if len(value) == 1:
            shape = [1]
            value = value[0]
            if dtype.name == 'int64':
                dtype = 'int32'
            attr = {'shape': shape, 'dtype': string(dtype), 'value': value}
            node.fluid_code.add_layer('fill_constant',
                                      inputs=None,
                                      output=node,
                                      param_attr=attr)

    def Split(self, node):
C
channingss 已提交
513
        val_input = self.graph.get_input_node(node, idx=0, copy=True)
C
update  
channingss 已提交
514 515 516 517 518 519 520 521 522 523 524 525 526
        var_outs = [val for val in node.layer.input]

        fluid_op = 'split'
        split = node.get_attr['split']
        axis = node.get_attr('axis', 0)
        attr = {'split': split, 'axis': axis, 'name': string(node.layer_name)}
        # generation
        node.fluid_code.add_layer('split',
                                  inputs=val_input,
                                  output=var_outs,
                                  param_attr=attr)

    def Reshape(self, node):
C
channingss 已提交
527 528
        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 已提交
529 530
        val_reshaped = self.graph.get_node(node.layer.output[0], copy=True)
        shape = None
C
channingss 已提交
531

C
update  
channingss 已提交
532 533 534 535 536
        if isinstance(val_shape, ONNXGraphDataNode):
            self.omit_nodes.append(val_shape.layer_name)

        # catch dynamic graph shape
        if isinstance(val_shape, ONNXGraphNode):
C
channingss 已提交
537 538
            shape, _, _ = self.decoder.onnx_graph.get_dynamic_shape(
                val_shape.layer_name)
C
update  
channingss 已提交
539
        if shape is None:
C
channingss 已提交
540
            shape = val_reshaped.out_shapes[0]
C
update  
channingss 已提交
541 542 543 544 545 546

        shape_dtype = val_shape.dtype

        if shape_dtype is None:
            _logger.warning(
                'in op %s(%s -> Reshape -> %s): '
C
channingss 已提交
547 548
                'dtype of input "shape" not inferred, int32 assumed',
                node.layer_name, val_x.layer_name, val_reshaped.layer_name)
C
update  
channingss 已提交
549 550
            shape_dtype = _np.dtype('int32')
        if shape is None:
C
channingss 已提交
551
            shape = [1, -1]
C
update  
channingss 已提交
552 553 554
            _logger.warning(
                'in %s(%s -> Reshape -> %s): '
                'input "shape" not inferred, use [1, -1] as dummy value, '
C
channingss 已提交
555 556
                'the behavior of Paddle fluid maybe undefined', node.layer_name,
                val_x.layer_name, val_reshaped.layer_name)
C
update  
channingss 已提交
557 558 559 560 561 562 563 564
        attr = {'shape': shape, 'name': string(node.layer_name)}

        node.fluid_code.add_layer('reshape',
                                  inputs=val_x,
                                  output=node,
                                  param_attr=attr)

    def Cast(self, node):
C
channingss 已提交
565
        val_input = self.graph.get_input_node(node, idx=0, copy=True)
C
update  
channingss 已提交
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
        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'
        attr = {'dtype': string(dtype)}
        node.fluid_code.add_layer('cast',
                                  inputs=val_input,
                                  output=node,
                                  param_attr=attr)

    def AveragePool(self, node):
C
channingss 已提交
582
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
C
channingss 已提交
583 584

        auto_pad = node.get_attr('auto_pad', 'NOTSET')
C
update  
channingss 已提交
585 586 587 588 589 590 591 592
        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))
        fluid_op = 'pool{}d'.format(poolnd)
        assert 2 <= poolnd <= 3, 'only pool2d and pool3d is supported'
C
channingss 已提交
593

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

C
channingss 已提交
596
        if auto_pad == "SAME_UPPER" or auto_pad == "SAME_LOWER":
C
channingss 已提交
597
            input_shape = val_x.out_shapes[0]
C
channingss 已提交
598 599 600 601 602 603
            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])
            attr = {"paddings": pad_h + pad_w, "pad_value": 0.0}

C
update  
channingss 已提交
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
        attr = {
            "pool_size": kernel_shape,
            "pool_type": string('avg'),
            "pool_stride": strides,
            "pool_padding": paddings,
            "ceil_mode": ceil_mode,
            "exclusive": 'True',
            "name": string(node.layer_name)
        }

        node.fluid_code.add_layer(fluid_op,
                                  inputs=val_x,
                                  output=node,
                                  param_attr=attr)

    def Concat(self, node):
        inputs = []
        for i in range(len(node.layer.input)):
C
channingss 已提交
622
            ipt = self.graph.get_input_node(node, idx=i, copy=True)
C
update  
channingss 已提交
623 624 625 626 627 628 629
            if isinstance(ipt, str):
                inputs.append(ipt)
            else:
                inputs.append(ipt.layer_name)
        axis = node.get_attr('axis')
        attr = {'axis': axis}
        node.fluid_code.add_layer('concat',
C
channingss 已提交
630
                                  inputs=inputs,
C
update  
channingss 已提交
631 632 633 634
                                  output=node,
                                  param_attr=attr)

    def Flatten(self, node):
C
channingss 已提交
635
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
C
update  
channingss 已提交
636 637 638 639 640 641 642 643
        axis = node.get_attr('axis', 1)
        attr = {"axis": str(axis), "name": string(node.layer_name)}
        node.fluid_code.add_layer('flatten',
                                  inputs=val_x,
                                  output=node,
                                  param_attr=attr)

    def Gemm(self, node):
C
channingss 已提交
644 645 646
        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 已提交
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663

        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
        val_mm = node.layer_name + '_mm'
        matmul_inputs = {"x": val_a, "y": val_b}
        attr_matmul = {
            "transpose_x": trans_a,
            "transpose_y": trans_b,
            "alpha": alpha,
            "name": string(val_mm)
        }
        node.fluid_code.add_layer('matmul',
                                  inputs=matmul_inputs,
                                  output=val_mm,
                                  param_attr=attr_matmul)
C
channingss 已提交
664

C
update  
channingss 已提交
665 666 667 668 669 670 671 672 673
        if beta != 0:
            if beta == 1.:
                add_inputs = {"x": val_mm, "y": val_c}
                attr = {"name": string(node.layer_name)}
                node.fluid_code.add_layer("elementwise_add",
                                          inputs=add_inputs,
                                          output=node,
                                          param_attr=attr)
            else:
C
channingss 已提交
674 675 676 677 678 679 680 681 682 683 684 685 686
                var_beta = node.layer_name + '_beta'
                matmul_beta_inputs = {"x": val_c, "y": var_beta}
                node.fluid_code.add_layer("Constant",
                                          inputs=matmul_beta_inputs,
                                          output=var_beta,
                                          param_attr={'value': beta})

                add_inputs = {"x": val_mm, "y": var_beta}
                attr = {"name": string(node.layer_name)}
                node.fluid_code.add_layer("elementwise_add",
                                          inputs=add_inputs,
                                          output=node,
                                          param_attr=attr)
C
update  
channingss 已提交
687 688

    def Add(self, node):
C
channingss 已提交
689 690
        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
update  
channingss 已提交
691 692 693 694 695 696 697 698 699 700 701
        inputs = {
            "x": val_x,
            "y": val_y,
        }
        attr = {"name": string(node.layer_name)}
        node.fluid_code.add_layer("elementwise_add",
                                  inputs=inputs,
                                  output=node,
                                  param_attr=attr)

    def Sum(self, node):
702
        val_inps = node.layer.input
703
        inputs = {
C
channingss 已提交
704 705
            "x": self.graph.get_input_node(node, idx=0, copy=True),
            "y": self.graph.get_input_node(node, idx=1, copy=True),
706 707
        }
        node.fluid_code.add_layer("elementwise_add", inputs=inputs, output=node)
708

C
channingss 已提交
709 710
        for idx, ipt in enumerate(val_inps[2:]):
            y = self.graph.get_input_node(node, idx=idx, copy=True)
711 712
            inputs = {
                "x": node.layer_name,
C
channingss 已提交
713
                "y": y,
714 715 716 717
            }
            node.fluid_code.add_layer("elementwise_add",
                                      inputs=inputs,
                                      output=node)
C
update  
channingss 已提交
718 719

    def MatMul(self, node):
C
channingss 已提交
720 721
        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
update  
channingss 已提交
722 723 724 725 726 727 728 729
        inputs = {"x": val_x, "y": val_y}
        attr = {"name": string(node.layer_name)}
        node.fluid_code.add_layer("matmul",
                                  inputs=inputs,
                                  output=node,
                                  param_attr=attr)

    def BatchNormalization(self, node):
C
channingss 已提交
730 731 732 733 734
        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 已提交
735 736 737 738 739 740 741 742 743

        self.omit_nodes.append(val_scale.layer_name)
        self.omit_nodes.append(val_b.layer_name)
        self.omit_nodes.append(val_mean.layer_name)
        self.omit_nodes.append(val_var.layer_name)

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

C
channingss 已提交
744 745
        # Attribute: spatial is used in BatchNormalization-1,6,7
        spatial = bool(node.get_attr('spatial'))
C
update  
channingss 已提交
746 747 748 749
        attr = {
            "momentum": momentum,
            "epsilon": epsilon,
            "data_layout": string('NCHW'),
C
channingss 已提交
750
            "is_test": True,
C
update  
channingss 已提交
751 752 753 754
            "param_attr": string(val_scale.layer_name),
            "bias_attr": string(val_b.layer_name),
            "moving_mean_name": string(val_mean.layer_name),
            "moving_variance_name": string(val_var.layer_name),
C
channingss 已提交
755
            "use_global_stats": spatial,
C
update  
channingss 已提交
756 757 758 759 760 761 762 763
            "name": string(node.layer_name)
        }
        node.fluid_code.add_layer("batch_norm",
                                  inputs=val_x,
                                  output=node,
                                  param_attr=attr)

    def Transpose(self, node):
C
channingss 已提交
764
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
C
update  
channingss 已提交
765 766 767 768 769 770 771
        perm = node.get_attr('perm')
        attr = {'perm': perm, "name": string(node.layer_name)}
        node.fluid_code.add_layer("transpose",
                                  inputs=val_x,
                                  output=node,
                                  param_attr=attr)

C
channingss 已提交
772
    def Mul(self, node):
C
channingss 已提交
773 774
        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 已提交
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
        val_y_shape = val_y.out_shapes[0]
        slice_idx = 0
        for dim in val_y_shape:
            if dim == 1:
                slice_idx += 1
            else:
                break
        attr = {"name": string(node.layer_name)}
        if slice_idx < len(val_y_shape) and slice_idx > 0:
            val_y_reshaped = val_y_shape[slice_idx:]
            var_y_reshaped = val_y.layer_name + '_reshaped'
            attr_reshaped = {
                'shape': val_y_reshaped,
                'name': string(var_y_reshaped)
            }
            node.fluid_code.add_layer('reshape',
                                      inputs=val_y,
                                      output=var_y_reshaped,
                                      param_attr=attr_reshaped)
            inputs = {'x': val_x, 'y': var_y_reshaped}
            node.fluid_code.add_layer("elementwise_mul",
                                      inputs=inputs,
                                      output=node,
                                      param_attr=attr)
        else:
            inputs = {'x': val_x, 'y': val_y}
            node.fluid_code.add_layer("elementwise_mul",
                                      inputs=inputs,
                                      output=node,
                                      param_attr=attr)

C
update  
channingss 已提交
806
    def Div(self, node):
C
channingss 已提交
807 808
        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 已提交
809 810 811 812 813 814 815
        val_y_shape = val_y.out_shapes[0]
        slice_idx = 0
        for dim in val_y_shape:
            if dim == 1:
                slice_idx += 1
            else:
                break
C
update  
channingss 已提交
816
        attr = {"name": string(node.layer_name)}
C
channingss 已提交
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
        if slice_idx < len(val_y_shape) and slice_idx > 0:
            val_y_reshaped = val_y_shape[slice_idx:]
            var_y_reshaped = val_y.layer_name + '_reshaped'
            attr_reshaped = {
                'shape': val_y_reshaped,
                'name': string(var_y_reshaped)
            }
            node.fluid_code.add_layer('reshape',
                                      inputs=val_y,
                                      output=var_y_reshaped,
                                      param_attr=attr_reshaped)
            inputs = {'x': val_x, 'y': var_y_reshaped}
            node.fluid_code.add_layer("elementwise_div",
                                      inputs=inputs,
                                      output=node,
                                      param_attr=attr)
        else:
            inputs = {'x': val_x, 'y': val_y}
            node.fluid_code.add_layer("elementwise_div",
                                      inputs=inputs,
                                      output=node,
                                      param_attr=attr)
C
update  
channingss 已提交
839 840

    def Relu(self, node):
C
channingss 已提交
841
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
C
update  
channingss 已提交
842 843 844 845 846 847 848
        attr = {"name": string(node.layer_name)}
        node.fluid_code.add_layer("relu",
                                  inputs=val_x,
                                  output=node,
                                  param_attr=attr)

    def PRelu(self, node):
C
channingss 已提交
849 850
        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 已提交
851

C
channingss 已提交
852 853 854 855 856 857 858 859 860 861
        mode = 'channel'
        shape_slope = val_slope.out_shapes[0]
        if len(shape_slope) == 1:
            mode = 'all'
        elif len(shape_slope) > 2:
            mode = 'element'
        attr = {
            "param_attr": string(val_slope.layer_name),
            'mode': string(mode)
        }
C
update  
channingss 已提交
862 863 864 865 866 867
        node.fluid_code.add_layer("prelu",
                                  inputs=val_x,
                                  output=node,
                                  param_attr=attr)

    def Squeeze(self, node):
C
channingss 已提交
868 869 870
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
        axes = node.get_attr('axes')
        attr = {'axes': axes, "name": string(node.layer_name)}
C
update  
channingss 已提交
871 872 873 874 875 876
        node.fluid_code.add_layer("squeeze",
                                  inputs=val_x,
                                  output=node,
                                  param_attr=attr)

    def Identity(self, node):
C
channingss 已提交
877
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
C
update  
channingss 已提交
878 879 880
        node.fluid_code.add_layer("assign", inputs=val_x, output=node)

    def MaxPool(self, node):
C
channingss 已提交
881
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
C
update  
channingss 已提交
882

C
channingss 已提交
883
        auto_pad = node.get_attr('auto_pad', 'NOTSET')
C
update  
channingss 已提交
884 885 886 887 888 889 890 891 892 893 894
        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
        fluid_op = 'pool{}d'.format(poolnd)
        assert 2 <= poolnd <= 3, 'only pool2d and pool3d is supported'
C
channingss 已提交
895

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

C
channingss 已提交
898
        if auto_pad == "SAME_UPPER" or auto_pad == "SAME_LOWER":
C
channingss 已提交
899
            input_shape = val_x.out_shapes[0]
C
channingss 已提交
900 901 902 903 904 905
            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])
            attr = {"paddings": pad_h + pad_w, "pad_value": 0.0}

C
update  
channingss 已提交
906 907 908 909 910 911 912 913 914 915 916 917 918 919
        attr = {
            "pool_size": kernel_shape,
            "pool_type": string("max"),
            "pool_stride": strides,
            "pool_padding": paddings,
            "ceil_mode": ceil_mode,
            "name": string(node.layer_name),
            "exclusive": False
        }
        node.fluid_code.add_layer(fluid_op,
                                  inputs=val_x,
                                  output=node,
                                  param_attr=attr)

C
channingss 已提交
920 921 922 923 924 925 926 927 928 929

#     def Tile(self, node):
#         pass

#     def Loop(self, node):
#         pass

#     def NonMaxSuppression(self, node):
#         pass

C
update  
channingss 已提交
930
    def GlobalAveragePool(self, node):
C
channingss 已提交
931
        val_x = self.graph.get_input_node(node, idx=0, copy=True)
C
update  
channingss 已提交
932
        val_y = self.graph.get_node(node.layer.output[0], copy=True)
C
channingss 已提交
933 934
        input_shape = val_x.out_shapes[0]
        output_shape = val_y.out_shapes[0]
C
update  
channingss 已提交
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
        assert input_shape is not None or output_shape is not None, 'poolnd not inferred'  # N
        if input_shape:
            poolnd = len(input_shape) - 2  # NC...
        elif output_shape:
            poolnd = len(output_shape) - 2  # NC...
        assert 2 <= poolnd <= 3, 'only pool2d and pool3d is supported'
        fluid_op = 'pool{}d'.format(poolnd)
        attr = {
            "pool_type": string("avg"),
            "global_pooling": True,
            "name": string(node.layer_name)
        }
        node.fluid_code.add_layer(fluid_op,
                                  inputs=val_x,
                                  output=node,
                                  param_attr=attr)

    def Conv(self, node):
C
channingss 已提交
953 954
        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 已提交
955 956 957 958 959 960
        val_y = self.graph.get_node(node.layer.output[0], copy=True)

        self.omit_nodes.append(val_w.layer_name)

        has_bias = len(node.layer.input) == 3
        if has_bias:
C
channingss 已提交
961
            val_b = self.graph.get_input_node(node, idx=2, copy=True)
C
update  
channingss 已提交
962 963 964
            self.omit_nodes.append(val_b.layer_name)
        auto_pad = node.get_attr('auto_pad', 'NOTSET')

C
channingss 已提交
965
        kernel_shape = node.get_attr('kernel_shape')
C
update  
channingss 已提交
966 967
        convnd = len(kernel_shape)
        assert 2 <= convnd <= 3, 'only conv2d and conv3d is supported'
C
channingss 已提交
968
        num_out_channels = val_w.out_shapes[0][0]  # OI...
C
update  
channingss 已提交
969 970 971 972 973 974 975
        fluid_op = 'conv{}d'.format(convnd)

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

C
channingss 已提交
976
        input_shape = val_x.out_shapes[0]
C
update  
channingss 已提交
977 978
        paddings, val_x = self._pad_if_asymmetric(node, pads, val_x)

C
channingss 已提交
979
        if auto_pad == "SAME_UPPER" or auto_pad == "SAME_LOWER":
C
update  
channingss 已提交
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
            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])
            attr = {"paddings": pad_h + pad_w, "pad_value": 0.0}

        attr = {
            "num_filters": num_out_channels,
            "filter_size": kernel_shape,
            "stride": strides,
            "padding": paddings,
            "dilation": dilations,
            "groups": num_groups,
            'param_attr': string(val_w.layer_name),
            "name": string(node.layer_name)
        }
        if has_bias:
            attr["bias_attr"] = string(val_b.layer_name)
        else:
            attr["bias_attr"] = False
        node.fluid_code.add_layer(fluid_op,
                                  inputs=val_x,
                                  output=node,
                                  param_attr=attr)
C
channingss 已提交
1004 1005

    def ConvTranspose(self, node):
C
channingss 已提交
1006 1007 1008
        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 = self.graph.get_input_node(node, idx=2, copy=True)
C
channingss 已提交
1009 1010 1011 1012 1013 1014 1015 1016

        self.omit_nodes.append(val_w.layer_name)
        self.omit_nodes.append(val_b.layer_name)

        val_y = self.graph.get_node(node.layer.output[0], copy=True)

        auto_pad = node.get_attr('auto_pad', 'NOTSET')
        out_padding = node.get_attr('output_padding', [0, 0])
C
channingss 已提交
1017
        kernel_shape = node.get_attr('kernel_shape')
C
channingss 已提交
1018 1019 1020
        assert kernel_shape, 'kernel_shape not inferred'
        convnd = len(kernel_shape)
        assert 2 <= convnd <= 3, 'only conv2d_transpose and conv3d_transpose supported'
C
channingss 已提交
1021
        num_out_channels = val_w.out_shapes[0][1]
C
channingss 已提交
1022 1023
        fluid_op = 'conv{}d_transpose'.format(convnd)

C
channingss 已提交
1024 1025 1026 1027 1028
        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 已提交
1029 1030 1031 1032

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

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

C
channingss 已提交
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
        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]
        attr = {
            'num_filters': num_out_channels,
            'output_size': output_size or None,
            'filter_size': kernel_shape,
            'padding': paddings,
            'stride': strides,
            'dilation': dilations,
            'groups': num_groups,
            'param_attr': string(val_w.layer_name),
            'bias_attr': string(val_b.layer_name),
            'name': string(node.layer_name),
        }
        node.fluid_code.add_layer(fluid_op,
                                  inputs=val_x,
                                  output=node,
                                  param_attr=attr)