caffe_op_mapper.py 33.3 KB
Newer Older
J
jiangjiajun 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#   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.
S
SunAhong1993 已提交
14 15

import numbers
S
SunAhong1993 已提交
16
import numpy as np
J
jiangjiajun 已提交
17 18
from x2paddle.decoder.caffe_decoder import CaffeGraph
from x2paddle.core.op_mapper import OpMapper
S
SunAhong1993 已提交
19 20 21
from x2paddle.core.util import *


J
jiangjiajun 已提交
22 23 24 25
class CaffeOpMapper(OpMapper):
    def __init__(self, decoder):
        super(CaffeOpMapper, self).__init__()
        self.graph = decoder.caffe_graph
S
SunAhong1993 已提交
26
        self.weights = dict()
J
jiangjiajun 已提交
27
        resolver = decoder.resolver
S
SunAhong1993 已提交
28 29 30 31
        if resolver.has_pycaffe():
            self.did_use_pb = False
        else:
            self.did_use_pb = True
S
SunAhong1993 已提交
32 33 34

    def run(self):
        print("Total nodes: {}".format(len(self.graph.topo_sort)))
J
jiangjiajun 已提交
35 36 37 38 39

        # check if ops in model are all supported
        if not self.op_checker():
            raise Exception("Model are not supported yet.")

S
SunAhong1993 已提交
40 41 42 43
        for node_name in self.graph.topo_sort:
            node = self.graph.get_node(node_name)
            op = node.layer_type
            if hasattr(self, op):
J
jiangjiajun 已提交
44 45
                func = getattr(self, op)
                func(node)
S
SunAhong1993 已提交
46 47 48 49

        for i in range(len(self.graph.topo_sort)):
            node_name = self.graph.topo_sort[i]
            node = self.graph.get_node(node_name)
S
SunAhong1993 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
            self.net_code += node.fluid_code.gen_codes()

    def adjust_parameters(self, node, data):
        if not self.did_use_pb:
            return data

        # When using the protobuf-backend, each parameter initially has four dimensions.
        # In certain cases (like FC layers), we want to eliminate the singleton dimensions.
        # This implementation takes care of the common cases. However, it does leave the
        # potential for future issues.
        # The Caffe-backend does not suffer from this problem.
        data = list(data)

        squeeze_indices = [1]  # Squeeze biases.
        if node.kind == NodeKind.InnerProduct:
            squeeze_indices.append(0)  # Squeeze FC.

        for idx in squeeze_indices:
            if idx >= len(data):
                continue
S
SunAhong1993 已提交
70

S
SunAhong1993 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
            d = data[idx]
            assert len(
                d.shape
            ) == 4, 'invalid shape[%s] from caffe when adjust_parameters' % (
                str(d.shape))

            shape_old = d.shape
            sq_axis = None
            if idx == 0:
                sq_axis = (0, 1)
            elif idx == 1:
                sq_axis = (0, 1, 2)
            else:
                continue

            data[idx] = np.squeeze(d, axis=sq_axis)
            shape_new = data[idx].shape
            if len(shape_old) != shape_new:
                debug('squeeze idx:%d, with kind:%s,name:%s' % \
                        (idx, node.kind, node.name))
        return data
S
SunAhong1993 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109

    @staticmethod
    def get_kernel_value(scalar, repeated, idx, default=None):
        if scalar:
            return scalar
        if repeated:
            if isinstance(repeated, numbers.Number):
                return repeated
            if len(repeated) == 1:
                # Same value applies to all spatial dimensions
                return int(repeated[0])
            assert idx < len(repeated)
            # Extract the value for the given spatial dimension
            return repeated[idx]
        if default is None:
            raise ValueError('Unable to determine kernel parameter!')
        return default

S
SunAhong1993 已提交
110
    def get_kernel_parameters(self, kind, params):
S
SunAhong1993 已提交
111 112
        assert kind in ['Convolution', 'Pooling', 'Deconvolution']

S
SunAhong1993 已提交
113 114 115 116 117 118 119 120
        k_h = self.get_kernel_value(params.kernel_h,
                                    params.kernel_size,
                                    0,
                                    default=1)
        k_w = self.get_kernel_value(params.kernel_w,
                                    params.kernel_size,
                                    1,
                                    default=1)
S
SunAhong1993 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
        s_h = self.get_kernel_value(params.stride_h,
                                    params.stride,
                                    0,
                                    default=1)
        s_w = self.get_kernel_value(params.stride_w,
                                    params.stride,
                                    1,
                                    default=1)
        p_h = self.get_kernel_value(params.pad_h, params.pad, 0, default=0)
        p_w = self.get_kernel_value(params.pad_w, params.pad, 1, default=0)
        dila_h = dila_w = 1
        group = 1
        c_o = 1
        if kind in ['Convolution', 'Deconvolution']:
            c_o = params.num_output
            group = params.group
            dila_len = len(params.dilation)
            if dila_len == 2:
                dila_h = params.dilation[0]
                dila_w = params.dilation[1]
            elif dila_len == 1:
                dila_h = dila_w = params.dilation[0]
            else:
                assert dila_len == 0, "invalid length[%s] of dilation in convolution" % (
                    dila_len)

        kernel = [k_h, k_w]
        stride = [s_h, s_w]
        pad = [p_h, p_w]
        dilation = [dila_h, dila_w]

        return c_o, kernel, stride, pad, dilation, group

S
SunAhong1993 已提交
154 155 156 157 158 159
    def get_input_name(self, node):
        if hasattr(node, "index"):
            return node.layer_name + "[{}]".format(node.index)
        else:
            return node.layer_name

S
SunAhong1993 已提交
160 161 162 163 164 165
    def is_BN(self, node):
        return True if node.layer_type == 'BatchNorm' else False

    def is_Scale(self, node):
        return True if node.layer_type == 'Scale' else False

S
SunAhong1993 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
    def Input(self, node):
        shape = list(node.layer.input_param.shape[0].dim)[1:]
        dtype = 'float32'
        attr = {
            'dtype': string(dtype),
            'shape': shape,
            'name': string(node.layer_name)
        }
        node.fluid_code.add_layer("data",
                                  inputs=None,
                                  output=node,
                                  param_attr=attr)

    def Convolution(self, node):
        data = node.data
S
SunAhong1993 已提交
181 182
        assert data is not None, 'The parameter of {} (type is {}) is not set. You need to use python package of caffe to set the default value.'.format(
            node.layer_name, node.layer_type)
S
SunAhong1993 已提交
183
        data = self.adjust_parameters(node, data)
S
SunAhong1993 已提交
184 185 186 187 188 189 190 191
        self.weights[node.layer_name + '_weights'] = data[0]
        if len(data) == 2:
            self.weights[node.layer_name + '_bias'] = data[1]
        params = node.layer.convolution_param
        channel, kernel, stride, pad, dilation, group = self.get_kernel_parameters(
            node.layer_type, params)
        assert len(node.inputs
                   ) == 1, 'The count of Convolution node\'s input is not 1.'
S
SunAhong1993 已提交
192
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
193 194 195 196 197
        if self.is_Scale(input):
            tmp = self.graph.get_bottom_node(input, idx=0, copy=True)
            if self.is_BN(tmp):
                input = tmp

S
SunAhong1993 已提交
198
        attr = {
S
SunAhong1993 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
            'filter_size':
            kernel,
            'num_filters':
            channel,
            'stride':
            stride,
            'padding':
            pad,
            'dilation':
            dilation,
            'groups':
            group,
            'name':
            string(node.layer_name),
            'param_attr':
            string(node.layer_name + '_weights'),
            'bias_attr':
            False if len(data) == 1 else string(node.layer_name + '_bias'),
S
SunAhong1993 已提交
217 218 219 220 221 222 223 224
        }
        node.fluid_code.add_layer("conv2d",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def Deconvolution(self, node):
        data = node.data
S
SunAhong1993 已提交
225 226
        assert data is not None, 'The parameter of {} (type is {}) is not set. You need to use python package of caffe to set the default value.'.format(
            node.layer_name, node.layer_type)
S
SunAhong1993 已提交
227
        data = self.adjust_parameters(node, data)
S
SunAhong1993 已提交
228 229 230 231 232 233 234 235
        self.weights[node.layer_name + '_weights'] = data[0]
        if len(data) == 2:
            self.weights[node.layer_name + '_bias'] = data[1]
        params = node.layer.convolution_param
        channel, kernel, stride, pad, dilation, group = self.get_kernel_parameters(
            node.layer_type, params)
        assert len(node.inputs
                   ) == 1, 'The count of Deconvolution node\'s input is not 1.'
S
SunAhong1993 已提交
236
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
237 238 239 240
        if self.is_Scale(input):
            tmp = self.graph.get_bottom_node(input, idx=0, copy=True)
            if self.is_BN(tmp):
                input = tmp
S
SunAhong1993 已提交
241
        attr = {
S
SunAhong1993 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
            'output_size':
            None,
            'filter_size':
            kernel,
            'num_filters':
            channel,
            'stride':
            stride,
            'padding':
            pad,
            'dilation':
            dilation,
            'groups':
            group,
            'name':
            string(node.layer_name),
            'param_attr':
            string(node.layer_name + '_weights'),
            'bias_attr':
            False if len(data) == 1 else string(node.layer_name + '_bias')
S
SunAhong1993 已提交
262 263 264 265 266 267 268 269
        }
        node.fluid_code.add_layer("conv2d_transpose",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def Pooling(self, node):
        params = node.layer.pooling_param
S
SunAhong1993 已提交
270 271
        global_pool = getattr(params, 'global_pooling', False)
        kernel_default = [1, 1]
S
SunAhong1993 已提交
272
        channel, kernel, stride, pad, dilation, group = self.get_kernel_parameters(
S
SunAhong1993 已提交
273
            node.layer_type, params)
S
SunAhong1993 已提交
274 275 276 277 278 279
        if params.pool == 0:
            pool_type = 'max'
        else:
            pool_type = 'avg'
        assert len(
            node.inputs) == 1, 'The count of Pooling node\'s input is not 1.'
S
SunAhong1993 已提交
280
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
281 282 283 284
        if self.is_Scale(input):
            tmp = self.graph.get_bottom_node(input, idx=0, copy=True)
            if self.is_BN(tmp):
                input = tmp
S
SunAhong1993 已提交
285 286 287 288 289 290 291
        attr = {
            'pool_size': kernel,
            'pool_stride': stride,
            'pool_padding': pad,
            'ceil_mode': True,
            'pool_type': string(pool_type),
            'exclusive': True,
S
SunAhong1993 已提交
292
            'global_pooling': global_pool,
S
SunAhong1993 已提交
293 294 295 296 297 298 299 300 301 302
            'name': string(node.layer_name)
        }
        node.fluid_code.add_layer("pool2d",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def ReLU(self, node):
        assert len(
            node.inputs) == 1, 'The count of ReLU node\'s input is not 1.'
S
SunAhong1993 已提交
303
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
304 305 306 307
        if self.is_Scale(input):
            tmp = self.graph.get_bottom_node(input, idx=0, copy=True)
            if self.is_BN(tmp):
                input = tmp
S
SunAhong1993 已提交
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
        attr = {'name': string(node.layer_name)}
        node.fluid_code.add_layer("relu",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def LRN(self, node):
        assert len(node.inputs) == 1, 'The count of LRN node\'s input is not 1.'
        params = node.layer.lrn_param
        # The window size must be an odd value. For a window
        # size of (2*n+1), Paddle defines depth_radius = n.
        assert params.local_size % 2 == 1
        # Caffe scales by (alpha/(2*n+1)), whereas Paddle
        # just scales by alpha (as does Krizhevsky's paper).
        # We'll account for that here.
        alpha = params.alpha / float(params.local_size)
S
SunAhong1993 已提交
324
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
325 326 327 328
        if self.is_Scale(input):
            tmp = self.graph.get_bottom_node(input, idx=0, copy=True)
            if self.is_BN(tmp):
                input = tmp
S
SunAhong1993 已提交
329 330 331 332 333 334 335 336 337 338 339 340 341 342
        attr = {
            'n': params.local_size,
            'k': 1.0,
            'alpha': alpha,
            'beta': params.beta,
            'name': string(node.layer_name)
        }
        node.fluid_code.add_layer("lrn",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def InnerProduct(self, node):
        data = node.data
S
SunAhong1993 已提交
343 344
        assert data is not None, 'The parameter of {} (type is {}) is not set. You need to use python package of caffe to set the default value.'.format(
            node.layer_name, node.layer_type)
S
SunAhong1993 已提交
345 346 347 348 349 350 351 352 353 354
        data = self.adjust_parameters(node, data)
        # Reshape the parameters to Paddle's ordering
        transpose_order = (1, 0)
        w = data[0]
        fc_shape = w.shape
        output_channels = fc_shape[0]
        w = w.reshape((output_channels, -1))
        w = w.transpose(transpose_order)
        data[0] = w

S
SunAhong1993 已提交
355 356 357 358 359 360 361 362
        self.weights[node.layer_name + '_weights'] = data[0]
        if len(data) == 2:
            self.weights[node.layer_name + '_bias'] = data[1]
        assert len(node.inputs
                   ) == 1, 'The count of InnerProduct node\'s input is not 1.'
        params = node.layer.inner_product_param
        assert params.axis == 1
        assert params.bias_term == True
S
SunAhong1993 已提交
363
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
364 365 366 367
        if self.is_Scale(input):
            tmp = self.graph.get_bottom_node(input, idx=0, copy=True)
            if self.is_BN(tmp):
                input = tmp
S
SunAhong1993 已提交
368
        attr = {
S
SunAhong1993 已提交
369 370 371 372 373 374 375 376 377 378
            'size':
            params.num_output,
            'name':
            string(node.layer_name),
            'act':
            None,
            'param_attr':
            string(node.layer_name + '_weights'),
            'bias_attr':
            False if len(data) == 1 else string(node.layer_name + '_bias')
S
SunAhong1993 已提交
379 380 381 382 383 384 385 386 387
        }
        node.fluid_code.add_layer("fc",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def Softmax(self, node):
        assert len(
            node.inputs) == 1, 'The count of Softmax node\'s input is not 1.'
S
SunAhong1993 已提交
388
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
389 390 391 392
        if self.is_Scale(input):
            tmp = self.graph.get_bottom_node(input, idx=0, copy=True)
            if self.is_BN(tmp):
                input = tmp
S
SunAhong1993 已提交
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
        params = node.layer.softmax_param
        axis = params.axis
        shape = node.input_shape[0]
        dims = len(shape)
        axis = axis + dims if axis < 0 else axis
        need_transpose = False
        if axis + 1 != dims:
            need_transpose = True
        if need_transpose:
            in_order = list(range(dims))
            in_order.remove(axis)
            in_order.append(axis)
            attr = {
                'perm': in_order,
                'name': string(node.layer_name + '_transpose_in')
            }
            node.fluid_code.add_layer("transpose",
                                      inputs=input,
                                      output=node,
                                      param_attr=attr)
        attr = {'name': string(node.layer_name + '_softmax')}
        node.fluid_code.add_layer("softmax",
                                  inputs=node if need_transpose else input,
                                  output=node,
                                  param_attr=attr)
        if need_transpose:
            out_order = [
                0,
            ] * dims
            for id, v in enumerate(in_order):
                out_order[v] = id
            attr = {
                'perm': out_order,
                'name': string(node.layer_name + '_transpose_out')
            }
            node.fluid_code.add_layer("transpose",
                                      inputs=node,
                                      output=node,
                                      param_attr=attr)
S
SunAhong1993 已提交
432 433 434 435 436

    def Slice(self, node):
        assert len(
            node.inputs) == 1, 'The count of Slice node\'s input is not 1.'
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
437 438 439 440
        if self.is_Scale(input):
            tmp = self.graph.get_bottom_node(input, idx=0, copy=True)
            if self.is_BN(tmp):
                input = tmp
S
SunAhong1993 已提交
441 442 443
        params = node.layer.slice_param
        axis = params.axis
        points = list(params.slice_point)
S
SunAhong1993 已提交
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
        maxint32 = 2147483647
        points = [0] + points
        points.append(maxint32)
        i = 0
        node.fluid_code.add_note('{} = []'.format(node.layer_name))
        for i in range(len(points)):
            attr = {
                'axes': [axis],
                'starts': [points[i]],
                'ends': [points[i + 1]],
                'name': string(node.layer_name + '_' + str(i))
            }
            node.fluid_code.add_layer("slice",
                                      inputs=input,
                                      output=string(node.layer_name + '_' +
                                                    str(i)),
                                      param_attr=attr)
            node.fluid_code.add_note('{}.append({})'.format(
                node.layer_name, node.layer_name + '_' + str(i)))
            if i == len(points) - 2:
                break
S
SunAhong1993 已提交
465 466 467

    def Concat(self, node):
        assert len(
S
SunAhong1993 已提交
468 469
            node.inputs
        ) > 1, 'The count of Concat node\'s input is not more than 1.'
S
SunAhong1993 已提交
470 471 472
        inputs = []
        for i in range(len(node.inputs)):
            input = self.graph.get_bottom_node(node, idx=i, copy=True)
S
SunAhong1993 已提交
473 474 475 476
            if self.is_Scale(input):
                tmp = self.graph.get_bottom_node(input, idx=0, copy=True)
                if self.is_BN(tmp):
                    input = tmp
S
SunAhong1993 已提交
477 478 479
            inputs.append(input)
        params = node.layer.concat_param
        axis = params.axis
S
SunAhong1993 已提交
480 481 482 483 484 485 486 487 488 489
        attr = {'axis': axis, 'name': string(node.layer_name)}
        node.fluid_code.add_layer("concat",
                                  inputs=inputs,
                                  output=node,
                                  param_attr=attr)

    def PReLU(self, node):
        assert len(
            node.inputs) == 1, 'The count of PReLU node\'s input is not 1.'
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
490 491 492 493
        if self.is_Scale(input):
            tmp = self.graph.get_bottom_node(input, idx=0, copy=True)
            if self.is_BN(tmp):
                input = tmp
S
SunAhong1993 已提交
494 495 496 497 498 499 500 501 502 503
        params = node.layer.prelu_param
        mode_bool = params.channel_shared
        if mode_bool:
            mode = 'all'
        else:
            mode = 'channel'
        data = node.data
        assert data is not None, 'The parameter of {} (type is {}) is not set. You need to use python package of caffe to set the default value.'.format(
            node.layer_name, node.layer_type)
        self.weights[node.layer_name + '_weights'] = data[0]
S
SunAhong1993 已提交
504
        attr = {
S
SunAhong1993 已提交
505 506 507
            'mode': mode,
            'param_attr': string(node.layer_name + '_weights'),
            'name': string(node.layer_name)
S
SunAhong1993 已提交
508
        }
S
SunAhong1993 已提交
509 510 511 512 513 514 515 516 517
        node.fluid_code.add_layer("prelu",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def Sigmoid(self, node):
        assert len(
            node.inputs) == 1, 'The count of PReLU node\'s input is not 1.'
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
518 519 520 521
        if self.is_Scale(input):
            tmp = self.graph.get_bottom_node(input, idx=0, copy=True)
            if self.is_BN(tmp):
                input = tmp
S
SunAhong1993 已提交
522 523 524 525 526 527 528 529 530 531
        attr = {'name': string(node.layer_name)}
        node.fluid_code.add_layer("sigmoid",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def AbsVal(self, node):
        assert len(
            node.inputs) == 1, 'The count of PReLU node\'s input is not 1.'
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
532 533 534 535
        if self.is_Scale(input):
            tmp = self.graph.get_bottom_node(input, idx=0, copy=True)
            if self.is_BN(tmp):
                input = tmp
S
SunAhong1993 已提交
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
        attr = {'name': string(node.layer_name)}
        node.fluid_code.add_layer("absval",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def Accuracy(self, node):
        assert len(
            node.inputs) == 2, 'The count of Accuracy node\'s input is not 2.'
        inputs = []
        inputs[0] = None
        inputs[1] = None
        i = 0
        for shape in node.input_shape:
            if shape[1] == 1:
S
SunAhong1993 已提交
551 552 553 554 555 556
                input = self.graph.get_bottom_node(node, idx=i, copy=True)
                if self.is_Scale(input):
                    tmp = self.graph.get_bottom_node(input, idx=0, copy=True)
                    if self.is_BN(tmp):
                        input = tmp
                inputs[1] = input
S
SunAhong1993 已提交
557
            else:
S
SunAhong1993 已提交
558 559 560 561 562 563
                input = self.graph.get_bottom_node(node, idx=i, copy=True)
                if self.is_Scale(input):
                    tmp = self.graph.get_bottom_node(input, idx=0, copy=True)
                    if self.is_BN(tmp):
                        input = tmp
                inputs[0] = input
S
SunAhong1993 已提交
564 565 566 567 568 569 570 571 572 573
            i += 1
        params = node.layer.accuracy_param
        top_k = params.top_k
        axis = params.axis
        ignore_label = params.ignore_label
        # TODO(syf)
        assert axis == 1, 'PaddlePaddle can not support the situation when the axis is not 1.'
        assert not ignore_label >= 0, 'PaddlePaddle can not support the situation when the model has ignore label.'
        attr = {'k': top_k}
        node.fluid_code.add_layer("accuracy",
S
SunAhong1993 已提交
574 575 576
                                  inputs=inputs,
                                  output=node,
                                  param_attr=attr)
S
SunAhong1993 已提交
577 578 579 580 581

    def TanH(self, node):
        assert len(
            node.inputs) == 1, 'The count of TanH node\'s input is not 1.'
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
582 583 584 585
        if self.is_Scale(input):
            tmp = self.graph.get_bottom_node(input, idx=0, copy=True)
            if self.is_BN(tmp):
                input = tmp
S
SunAhong1993 已提交
586 587 588 589 590 591 592 593 594 595 596 597
        attr = {'name': string(node.layer_name)}
        node.fluid_code.add_layer("tanh",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def Eltwise(self, node):
        assert len(
            node.inputs) == 2, 'The count of TanH node\'s input is not 2.'
        params = node.layer.eltwise_param
        mode = params.operation
        inputs = []
S
SunAhong1993 已提交
598 599 600 601 602 603 604 605 606 607 608 609
        input0 = self.graph.get_bottom_node(node, idx=0, copy=True)
        if self.is_Scale(input0):
            tmp = self.graph.get_bottom_node(input0, idx=0, copy=True)
            if self.is_BN(tmp):
                input0 = tmp
        inputs.append(input0)
        input1 = self.graph.get_bottom_node(node, idx=1, copy=True)
        if self.is_Scale(input1):
            tmp = self.graph.get_bottom_node(input1, idx=0, copy=True)
            if self.is_BN(tmp):
                input1 = tmp
        inputs.append(input1)
S
SunAhong1993 已提交
610
        if mode == 0:
S
SunAhong1993 已提交
611 612 613
            inputs_dict = {}
            inputs_dict['x'] = inputs[0]
            inputs_dict['y'] = inputs[1]
S
SunAhong1993 已提交
614 615
            attr = {'act': None, 'name': string(node.layer_name)}
            node.fluid_code.add_layer("elementwise_mul",
S
SunAhong1993 已提交
616
                                      inputs=inputs_dict,
S
SunAhong1993 已提交
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
                                      output=node,
                                      param_attr=attr)
        elif mode == 1:
            if hasattr(params, 'coeff') and len(params.coeff) == 2:
                coeff = params.coeff
                input1_name = self.get_input_name(inputs[0])
                attr = {
                    'shape': [1],
                    'value': coeff[0],
                    'dtype': '{}.dtype'.format(input1_name)
                }
                node.fluid_code.add_layer("fill_constant",
                                          inputs=None,
                                          output=node.layer_name + '_const1',
                                          param_attr=attr)
                attr = {'act': None, 'name': string(node.layer_name + '_mul1')}
                node.fluid_code.add_layer("elementwise_mul",
                                          inputs=input1_name + ', ' +
                                          node.layer_name + '_const1',
                                          output=node.layer_name + '_mul1',
                                          param_attr=attr)
                input2_name = self.get_input_name(inputs[1])
                attr = {
                    'shape': [1],
                    'value': coeff[1],
                    'dtype': '{}.dtype'.format(input2_name)
                }
                node.fluid_code.add_layer("fill_constant",
                                          inputs=None,
                                          output=node.layer_name + '_const2',
                                          param_attr=attr)
                attr = {'act': None, 'name': string(node.layer_name + '_mul2')}
                node.fluid_code.add_layer("elementwise_mul",
                                          inputs=input2_name + ', ' +
                                          node.layer_name + '_const2',
                                          output=node.layer_name + '_mul2',
                                          param_attr=attr)

                attr = {'act': None, 'name': string(node.layer_name)}
                node.fluid_code.add_layer("elementwise_add",
                                          inputs='{}_mul1, {}_mul2'.format(
                                              node.layer_name, node.layer_name),
                                          output=node,
                                          param_attr=attr)
            else:
S
SunAhong1993 已提交
662 663 664
                inputs_dict = {}
                inputs_dict['x'] = inputs[0]
                inputs_dict['y'] = inputs[1]
S
SunAhong1993 已提交
665 666
                attr = {'act': None, 'name': string(node.layer_name)}
                node.fluid_code.add_layer("elementwise_add",
S
SunAhong1993 已提交
667
                                          inputs=inputs_dict,
S
SunAhong1993 已提交
668 669 670
                                          output=node,
                                          param_attr=attr)
        else:
S
SunAhong1993 已提交
671 672 673
            inputs_dict = {}
            inputs_dict['x'] = inputs[0]
            inputs_dict['y'] = inputs[1]
S
SunAhong1993 已提交
674 675
            attr = {'act': None, 'name': string(node.layer_name)}
            node.fluid_code.add_layer("elementwise_max",
S
SunAhong1993 已提交
676
                                      inputs=inputs_dict,
S
SunAhong1993 已提交
677 678 679 680 681 682 683 684
                                      output=node,
                                      param_attr=attr)

    def BatchNorm(self, node):
        assert len(node.inputs) == 1 and len(
            node.outputs
        ) == 1, 'The count of BatchNorm node\'s input and output is not 1.'
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
685 686 687 688
        if self.is_Scale(input):
            tmp = self.graph.get_bottom_node(input, idx=0, copy=True)
            if self.is_BN(tmp):
                input = tmp
S
SunAhong1993 已提交
689
        params = node.layer.batch_norm_param
S
SunAhong1993 已提交
690
        if hasattr(params, 'eps'):
S
SunAhong1993 已提交
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
            eps = params.eps
        else:
            eps = 1e-5
        assert len(node.data) == 3
        node.data = [np.squeeze(i) for i in node.data]
        mean, variance, scale = node.data
        # Prescale the stats
        scaling_factor = 1.0 / scale if scale != 0 else 0
        mean *= scaling_factor
        variance *= scaling_factor
        self.weights[node.layer_name + '_mean'] = mean
        self.weights[node.layer_name + '_variance'] = variance
        if self.graph.get_node(node.outputs[0]).layer_type == 'Scale':
            data = self.graph.get_node(node.outputs[0]).data
            self.weights[node.layer_name + '_scale'] = np.squeeze(data[0])
            self.weights[node.layer_name + '_offset'] = np.squeeze(data[1])
            attr = {
                'is_test': True,
                'param_attr': string(node.layer_name + '_scale'),
                'bias_attr': string(node.layer_name + '_offset'),
                'moving_mean_name': string(node.layer_name + '_mean'),
                'moving_variance_name': string(node.layer_name + '_variance'),
                'epsilon': eps,
                'name': string(node.layer_name)
            }
        else:
            attr = {
                'is_test': True,
                'param_attr': None,
                'bias_attr': None,
                'moving_mean_name': string(node.layer_name + '_mean'),
                'moving_variance_name': string(node.layer_name + '_variance'),
                'epsilon': eps,
                'name': string(node.layer_name)
            }
        node.fluid_code.add_layer("batch_norm",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def Scale(self, node):
        assert len(
            node.outputs) == 1, 'The count of Scale node\'s output is not 1.'
        if len(node.inputs) == 1 and self.graph.get_node(
                node.inputs[0]).layer_type == 'BatchNorm':
            return
        else:
            self.weights[node.layer_name + '_scale'] = np.squeeze(nose.data[0])
            self.weights[node.layer_name + '_offset'] = np.squeeze(node.data[1])
            params = node.layer.scale_params
            axis = params.axis
            num_axes = params.num_axes
            assert num_axes == 1, "layer scale not support this num_axes[%d] now" % (
                num_axes)
            inputs = []
            if len(node.inputs) == 2:
                # for two tensor, here resets axis to 1. Maybe there is a bug for unkown case.
                axis = 1
                bias_shape = node.input_shape[0][axis:axis + num_axes]
                input0 = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
751 752 753 754
                if self.is_Scale(input0):
                    tmp = self.graph.get_bottom_node(input0, idx=0, copy=True)
                    if self.is_BN(tmp):
                        input0 = tmp
S
SunAhong1993 已提交
755
                input1 = self.graph.get_bottom_node(node, idx=1, copy=True)
S
SunAhong1993 已提交
756 757 758 759
                if self.is_Scale(input1):
                    tmp = self.graph.get_bottom_node(input1, idx=0, copy=True)
                    if self.is_BN(tmp):
                        input1 = tmp
S
SunAhong1993 已提交
760 761 762 763 764 765 766 767 768 769
                inputs.append(input0)
                inputs.append(input1)
                attr = {'axis': axis, 'name': string(node.layer_name + '_mul')}
                node.fluid_code.add_layer("elementwise_mul",
                                          inputs=inputs,
                                          output=node.layer_name + '_mul',
                                          param_attr=attr)
            else:
                bias_shape = node.input_shape[0][axis:axis + num_axes]
                input0 = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
770 771 772 773
                if self.is_Scale(input0):
                    tmp = self.graph.get_bottom_node(input0, idx=0, copy=True)
                    if self.is_BN(tmp):
                        input0 = tmp
S
SunAhong1993 已提交
774 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 806 807 808 809 810 811 812 813
                input0_name = self.get_input_name(input0)
                attr = {
                    'dtype': '{}.dtype'.formatr(input0_name),
                    'shape': bias_shape,
                    'name': string(node.layer_name + '_cparam1'),
                    'attr': string(node.layer_name + '_scale'),
                    'is_bias': True,
                    'default_initializer': 'Constant(value=1.0)'
                }
                node.fluid_code.add_layer("create_parameter",
                                          inputs=None,
                                          output=node,
                                          param_attr=attr)
                inputs.append(input0)
                inputs.append(node)
                attr = {'axis': axis, 'name': string(node.layer_name + '_mul')}
                node.fluid_code.add_layer("elementwise_mul",
                                          inputs=inputs,
                                          output=node.layer_name + '_mul',
                                          param_attr=attr)
            scale_shape = bias_shape
            input0_name = self.get_input_name(input0)
            attr = {
                'dtype': '{}.dtype'.formatr(input0_name),
                'shape': scale_shape,
                'name': string(node.layer_name + '_cparam2'),
                'attr': string(node.layer_name + '_offset'),
                'is_bias': True,
                'default_initializer': 'Constant(value=1.0)'
            }
            node.fluid_code.add_layer("create_parameter",
                                      inputs=None,
                                      output=node.layer_name + '_offset_param',
                                      param_attr=attr)
            attr = {'axis': axis, 'name': string(node.layer_name + '_add')}
            node.fluid_code.add_layer("elementwise_add",
                                      inputs='{}_mul, {}_offset_param'.format(
                                          node.layer_name, node.layer_name),
                                      output=node,
                                      param_attr=attr)