caffe_op_mapper.py 58.2 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
from x2paddle.core.util import *
S
SunAhong1993 已提交
20
from x2paddle.op_mapper.caffe_custom_layer import *
S
SunAhong1993 已提交
21 22


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

S
SunAhong1993 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
    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
            if not hasattr(self, op) and op not in custom_layers:
                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

S
SunAhong1993 已提交
51 52
    def run(self):
        print("Total nodes: {}".format(len(self.graph.topo_sort)))
J
jiangjiajun 已提交
53 54 55
        # check if ops in model are all supported
        if not self.op_checker():
            raise Exception("Model are not supported yet.")
S
SunAhong1993 已提交
56 57 58 59
        for node_name in self.graph.topo_sort:
            node = self.graph.get_node(node_name)
            op = node.layer_type
            if hasattr(self, op):
S
SunAhong1993 已提交
60
                self.set_shape(node)
J
jiangjiajun 已提交
61 62
                func = getattr(self, op)
                func(node)
S
SunAhong1993 已提交
63 64 65 66 67 68 69
            elif op in custom_layers:
                self.set_shape(node, is_fluid_op=False)
                self.deal_custom_layer(node)
            else:
                raise Exception("Model are not supported yet.")
        for key in self.mylayers:
            self.net_code.append(self.mylayers[key])
S
SunAhong1993 已提交
70 71 72 73

        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 已提交
74 75
            self.net_code += node.fluid_code.gen_codes()

S
SunAhong1993 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
    def set_shape(self, node, is_fluid_op=True):
        inputs = node.inputs
        input_shape = []
        for i, nm in enumerate(inputs):
            last_node = self.graph.get_node(nm)
            tmp = node.layer.bottom[i]
            idx = list(last_node.layer.top).index(tmp)
            input_shape.append(last_node.output_shape[idx])
        node.set_input_shape(input_shape)
        if is_fluid_op:
            node.set_output_shape(input_shape)
        else:
            node.set_output_shape(compute_output_shape(node),
                                  is_input=is_fluid_op)

    def adjust_parameters(self, node):
        data = node.data
S
SunAhong1993 已提交
93 94 95 96 97 98 99 100 101 102
        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.
S
SunAhong1993 已提交
103
        if node.layer_type == 'InnerProduct':
S
SunAhong1993 已提交
104 105 106 107 108
            squeeze_indices.append(0)  # Squeeze FC.

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

S
SunAhong1993 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
            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
S
SunAhong1993 已提交
127 128
            print('shape-old' + str(shape_old))
            print('shape-new' + str(shape_new))
S
SunAhong1993 已提交
129
            if len(shape_old) != shape_new:
S
SunAhong1993 已提交
130 131
                print('squeeze idx:%d, with kind:%s,name:%s' % \
                        (idx, node.layer_type, node.layer.name))
S
SunAhong1993 已提交
132
        return data
S
SunAhong1993 已提交
133

S
SunAhong1993 已提交
134
    def get_kernel_parameters(self, kind, params):
S
SunAhong1993 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
        assert kind in [
            'Convolution', 'Pooling', 'Deconvolution', 'ConvolutionDepthwise'
        ]
        [k_h, k_w] = [1, 1]
        print(params.kernel_size)
        if isinstance(params.kernel_size, numbers.Number):
            [k_h, k_w] = [params.kernel_size] * 2
        else:
            k_h = params.kernel_h if params.kernel_h else params.kernel_size[0]
            k_w = params.kernel_w if params.kernel_w else params.kernel_size[
                len(params.kernel_size) - 1]
        [s_h, s_w] = [1, 1]
        if isinstance(params.stride, numbers.Number):
            [s_h, s_w] = [params.stride] * 2
        else:
            s_h = params.stride_h if params.stride_h else params.stride[0]
            s_w = params.stride_w if params.stride_w else params.stride[
                len(params.stride) - 1]
        [p_h, p_w] = [0, 0]
        if isinstance(params.pad, numbers.Number):
            [p_h, p_w] = [params.pad] * 2
        else:
            p_h = params.pad_h if params.pad_h else params.pad[0]
            p_w = params.pad_w if params.pad_w else params.pad[len(params.pad) -
                                                               1]
S
SunAhong1993 已提交
160 161 162
        dila_h = dila_w = 1
        group = 1
        c_o = 1
S
SunAhong1993 已提交
163
        if kind in ['Convolution', 'Deconvolution', 'ConvolutionDepthwise']:
S
SunAhong1993 已提交
164 165 166 167 168 169 170 171 172 173
            c_o = params.num_output
            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)
S
SunAhong1993 已提交
174 175
        if kind in ['Convolution', 'Deconvolution']:
            group = params.group
S
SunAhong1993 已提交
176 177 178 179 180 181
        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 已提交
182 183 184 185 186 187
    def get_input_name(self, node):
        if hasattr(node, "index"):
            return node.layer_name + "[{}]".format(node.index)
        else:
            return node.layer_name

S
SunAhong1993 已提交
188 189 190 191 192 193
    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 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
    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 已提交
209 210
        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 已提交
211
        data = self.adjust_parameters(node)
S
SunAhong1993 已提交
212 213 214 215 216 217 218 219
        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 已提交
220
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
221 222 223 224 225
        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 已提交
226
        attr = {
S
SunAhong1993 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
            '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 已提交
245 246 247 248 249 250 251 252
        }
        node.fluid_code.add_layer("conv2d",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def Deconvolution(self, node):
        data = node.data
S
SunAhong1993 已提交
253 254
        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 已提交
255
        data = self.adjust_parameters(node)
S
SunAhong1993 已提交
256 257 258 259 260 261 262 263
        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 已提交
264
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
265 266 267 268
        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 已提交
269
        attr = {
S
SunAhong1993 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
            '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 已提交
290 291 292 293 294 295 296 297
        }
        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 已提交
298
        ceil_mode = getattr(params, 'ceil_mode', True)
S
SunAhong1993 已提交
299 300
        global_pool = getattr(params, 'global_pooling', False)
        kernel_default = [1, 1]
S
SunAhong1993 已提交
301
        channel, kernel, stride, pad, dilation, group = self.get_kernel_parameters(
S
SunAhong1993 已提交
302
            node.layer_type, params)
S
SunAhong1993 已提交
303 304 305 306 307 308
        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 已提交
309
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
310 311 312 313
        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 已提交
314 315 316 317
        attr = {
            'pool_size': kernel,
            'pool_stride': stride,
            'pool_padding': pad,
S
SunAhong1993 已提交
318
            'ceil_mode': ceil_mode,
S
SunAhong1993 已提交
319 320
            'pool_type': string(pool_type),
            'exclusive': True,
S
SunAhong1993 已提交
321
            'global_pooling': global_pool,
S
SunAhong1993 已提交
322 323 324 325 326 327 328 329 330 331
            '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 已提交
332
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
333 334 335 336
        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 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
        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 已提交
353
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
354 355 356 357
        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 已提交
358 359 360 361 362 363 364 365 366 367 368 369 370 371
        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 已提交
372 373
        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 已提交
374
        data = self.adjust_parameters(node)
S
SunAhong1993 已提交
375 376 377 378 379 380 381 382 383
        # 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 已提交
384 385 386 387 388 389 390 391
        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 已提交
392
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
393 394 395 396
        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 已提交
397
        attr = {
S
SunAhong1993 已提交
398 399 400 401 402 403 404 405 406 407
            '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 已提交
408 409 410 411 412 413 414 415 416
        }
        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 已提交
417
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
S
SunAhong1993 已提交
418 419 420 421
        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 已提交
422 423 424 425 426
        params = node.layer.softmax_param
        axis = params.axis
        shape = node.input_shape[0]
        dims = len(shape)
        axis = axis + dims if axis < 0 else axis
S
SunAhong1993 已提交
427
        attr = {'axis': axis, 'name': string(node.layer_name + '_softmax')}
S
SunAhong1993 已提交
428
        node.fluid_code.add_layer("softmax",
S
SunAhong1993 已提交
429
                                  inputs=input,
S
SunAhong1993 已提交
430 431
                                  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
        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]],
S
SunAhong1993 已提交
453
                'ends': [points[i + 1]]
S
SunAhong1993 已提交
454 455 456
            }
            node.fluid_code.add_layer("slice",
                                      inputs=input,
S
SunAhong1993 已提交
457
                                      output=node.layer_name + '_' + str(i),
S
SunAhong1993 已提交
458 459 460 461 462
                                      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 已提交
463 464 465

    def Concat(self, node):
        assert len(
S
SunAhong1993 已提交
466 467
            node.inputs
        ) > 1, 'The count of Concat node\'s input is not more than 1.'
S
SunAhong1993 已提交
468 469 470
        inputs = []
        for i in range(len(node.inputs)):
            input = self.graph.get_bottom_node(node, idx=i, copy=True)
S
SunAhong1993 已提交
471 472 473 474
            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 已提交
475 476 477
            inputs.append(input)
        params = node.layer.concat_param
        axis = params.axis
S
SunAhong1993 已提交
478 479 480 481 482 483 484 485 486 487
        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 已提交
488 489 490 491
        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 已提交
492 493 494 495 496 497 498 499 500 501
        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 已提交
502
        attr = {
S
SunAhong1993 已提交
503
            'mode': string(mode),
S
SunAhong1993 已提交
504 505
            'param_attr': string(node.layer_name + '_weights'),
            'name': string(node.layer_name)
S
SunAhong1993 已提交
506
        }
S
SunAhong1993 已提交
507 508 509 510 511 512 513 514 515
        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 已提交
516 517 518 519
        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 已提交
520 521 522 523 524 525 526 527 528 529
        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 已提交
530 531 532 533
        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 已提交
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
        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 已提交
549 550 551 552 553 554
                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 已提交
555
            else:
S
SunAhong1993 已提交
556 557 558 559 560 561
                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 已提交
562 563 564 565 566 567 568 569 570 571
            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 已提交
572 573 574
                                  inputs=inputs,
                                  output=node,
                                  param_attr=attr)
S
SunAhong1993 已提交
575 576 577 578 579

    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 已提交
580 581 582 583
        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 已提交
584 585 586 587 588 589 590 591 592 593 594 595
        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 已提交
596 597 598 599 600 601 602 603 604 605 606 607
        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 已提交
608
        if mode == 0:
S
SunAhong1993 已提交
609 610 611
            inputs_dict = {}
            inputs_dict['x'] = inputs[0]
            inputs_dict['y'] = inputs[1]
S
SunAhong1993 已提交
612 613
            attr = {'act': None, 'name': string(node.layer_name)}
            node.fluid_code.add_layer("elementwise_mul",
S
SunAhong1993 已提交
614
                                      inputs=inputs_dict,
S
SunAhong1993 已提交
615 616 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
                                      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 已提交
660 661 662
                inputs_dict = {}
                inputs_dict['x'] = inputs[0]
                inputs_dict['y'] = inputs[1]
S
SunAhong1993 已提交
663 664
                attr = {'act': None, 'name': string(node.layer_name)}
                node.fluid_code.add_layer("elementwise_add",
S
SunAhong1993 已提交
665
                                          inputs=inputs_dict,
S
SunAhong1993 已提交
666 667 668
                                          output=node,
                                          param_attr=attr)
        else:
S
SunAhong1993 已提交
669 670 671
            inputs_dict = {}
            inputs_dict['x'] = inputs[0]
            inputs_dict['y'] = inputs[1]
S
SunAhong1993 已提交
672 673
            attr = {'act': None, 'name': string(node.layer_name)}
            node.fluid_code.add_layer("elementwise_max",
S
SunAhong1993 已提交
674
                                      inputs=inputs_dict,
S
SunAhong1993 已提交
675 676 677 678 679 680 681 682
                                      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 已提交
683 684 685 686
        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 已提交
687
        params = node.layer.batch_norm_param
S
SunAhong1993 已提交
688
        if hasattr(params, 'eps'):
S
SunAhong1993 已提交
689 690 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
            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(
S
SunAhong1993 已提交
731
            node.inputs) == 1, 'The count of Scale node\'s input is not 1.'
S
SunAhong1993 已提交
732 733 734 735 736 737
        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])
S
SunAhong1993 已提交
738
            params = node.layer.scale_param
S
SunAhong1993 已提交
739 740 741 742 743 744 745 746 747 748
            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 已提交
749 750 751 752
                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 已提交
753
                input1 = self.graph.get_bottom_node(node, idx=1, copy=True)
S
SunAhong1993 已提交
754 755 756 757
                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 已提交
758 759 760 761 762 763 764 765 766 767
                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 已提交
768 769 770 771
                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 已提交
772 773 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
                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)
S
SunAhong1993 已提交
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057

    def Reshape(self, node):
        assert len(node.inputs) == 1 and len(
            node.outputs
        ) == 1, 'The count of Reshape node\'s input and output is not 1.'
        input = self.graph.get_bottom_node(node, idx=0, copy=True)
        top_count = len(input.layer.top)
        if self.is_Scale(input):
            tmp = self.graph.get_bottom_node(input, idx=0, copy=True)
            if self.is_BN(tmp):
                input = tmp
        is_inplace, = False if top_count == 1 else True
        output_shape = node.output_shape[0]
        attr = {
            'shape': output_shape,
            'inplace': is_inplace,
            'name': string(node.layer_name)
        }
        node.fluid_code.add_layer("reshape",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def ArgMax(self, node):
        assert len(node.inputs) == 1 and len(
            node.outputs
        ) == 1, 'The count of ArgMax node\'s input and output is not 1.'
        input = self.graph.get_bottom_node(node, idx=0, 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
        input_shape = node.input_shape[0]
        params = node.layer.argmax_param
        out_max_val = params.out_max_val if hasattr(params,
                                                    out_max_val) else False
        top_k = params.top_k if hasattr(params, top_k) else 1
        axis = parmas.axis if hasattr(params, axis) else -1
        if axis < 0:
            axis += len(input_shape)
        if out_max_val is True:
            attr = {'k': top_k, 'name': string(node.layer_name + '_topk')}
            node.fluid_code.add_layer("topk",
                                      inputs=input,
                                      output='{}_topk_var, {}_index_var'.format(
                                          node.layer_name, node.layer_name),
                                      param_attr=attr)
            attr = {'dtype': '{}_topk_var.dtype'.format(node.layer_name)}
            node.fluid_code.add_layer(
                "cast",
                inputs='{}_index_var'.format(node.layer_name),
                output='{}_index_var'.format(node.layer_name),
                param_attr=attr)
            attr = {'axis': axis, 'name': string(node.layer_name)}
            node.fluid_code.add_layer("concat",
                                      inputs='{}_topk_var, {}_index_var'.format(
                                          node.layer_name, node.layer_name),
                                      output=node,
                                      param_attr=attr)
        else:
            attr = {'k': top_k, 'name': string(node.layer_name)}
            node.fluid_code.add_layer("topk",
                                      inputs=input,
                                      output='_, {}'.format(node.layer_name),
                                      param_attr=attr)

    def Axpy(self, node):
        assert len(
            node.inputs) == 3, 'The count of Axpy node\'s input is not 3.'
        alpha = self.graph.get_bottom_node(node, idx=0, copy=True)
        if self.is_Scale(alpha):
            tmp = self.graph.get_bottom_node(alpha, idx=0, copy=True)
            if self.is_BN(tmp):
                alpha = tmp
        x = self.graph.get_bottom_node(node, idx=1, copy=True)
        if self.is_Scale(x):
            tmp = self.graph.get_bottom_node(x, idx=0, copy=True)
            if self.is_BN(tmp):
                x = tmp
        y = self.graph.get_bottom_node(node, idx=2, copy=True)
        if self.is_Scale(y):
            tmp = self.graph.get_bottom_node(y, idx=0, copy=True)
            if self.is_BN(tmp):
                y = tmp
        attr = {'axis': 0, 'name': string(node.layer_name + '_mul')}
        node.fluid_code.add_layer("elementwise_mul",
                                  inputs={
                                      'x': alpha,
                                      'y': x
                                  },
                                  output=node,
                                  param_attr=attr)
        attr = {'name': string(node.layer_name + '_add')}
        node.fluid_code.add_layer("elementwise_add",
                                  inputs={
                                      'x': node,
                                      'y': y
                                  },
                                  output=node,
                                  param_attr=attr)

    def Crop(self, node):
        assert len(
            node.inputs) == 2, 'The count of Crop node\'s input is not 2.'
        input = self.graph.get_bottom_node(node, idx=0, 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
        example = self.graph.get_bottom_node(node, idx=1, copy=True)
        if self.is_Scale(example):
            tmp = self.graph.get_bottom_node(example, idx=0, copy=True)
            if self.is_BN(tmp):
                example = tmp
        params = node.layer.crop_param
        axis = parmas.axis
        input_shape = node.input_shape[0]
        if axis < 0:
            axis += len(input_shape)
        offset_real = [0] * len(input_shape)
        if hasattr(params, offset):
            offset = list(params.offset)
            assert (len(input_shape) - axis) == len(
                offset), "invalid offset[%s] in crop layer" % (str(offset))
            offset_real = [0] * axis + offset
        attr = {'offsets': offset_real, 'name': string(node.layer_name)}
        node.fluid_code.add_layer("crop",
                                  inputs={
                                      'x': input,
                                      'y': example
                                  },
                                  output=node,
                                  param_attr=attr)

    def DetectionOutput(self, node):
        assert len(
            node.inputs
        ) == 3, 'The count of DetectionOutput node\'s input is not 3.'
        mbox_loc = self.graph.get_bottom_node(node, idx=0, copy=True)
        if self.is_Scale(mbox_loc):
            tmp = self.graph.get_bottom_node(mbox_loc, idx=0, copy=True)
            if self.is_BN(tmp):
                mbox_loc = tmp
        mbox_conf_flatten = self.graph.get_bottom_node(node, idx=1, copy=True)
        if self.is_Scale(mbox_conf_flatten):
            tmp = self.graph.get_bottom_node(mbox_conf_flatten,
                                             idx=0,
                                             copy=True)
            if self.is_BN(tmp):
                mbox_conf_flatten = tmp
        mbox_priorbox = self.graph.get_bottom_node(node, idx=2, copy=True)
        if self.is_Scale(mbox_priorbox):
            tmp = self.graph.get_bottom_node(mbox_priorbox, idx=0, copy=True)
            if self.is_BN(tmp):
                mbox_priorbox = tmp
        params = node.layer.detection_output_param
        nms_threshold = 0.3
        top_k = 10
        eta = 1.0
        if hasattr(params, 'nms_param'):
            nms_threshold = getattr(params.nms_param, 'nms_threshold', 0.3)
            top_k = getattr(params.nms_param, 'top_k', 10)
            eta = getattr(params.nms_param, 'eta', 1.0)
        background_label = getattr(params, 'background_label_id', 0)
        share_location = getattr(params, 'share_location', True)
        keep_top_k = getattr(params, 'keep_top_k', 100)
        confidence_threshold = getattr(params, 'confidence_threshold', 0.1)
        attr = {
            'num_or_sections': 2,
            'dim': 1,
            'name': string(node.layer_name + '_split')
        }
        node.fluid_code.add_layer("split",
                                  inputs=mbox_priorbox,
                                  output='mbox_priorbox_list',
                                  param_attr=attr)
        node.fluid_code.add_note('pb = mbox_priorbox_list[0]')
        node.fluid_code.add_note('pbv = mbox_priorbox_list[1]')
        attr = {'shape': [-1, 4], 'name': string(node.layer_name + '_reshape1')}
        node.fluid_code.add_layer("reshape",
                                  inputs='pb',
                                  output='pb',
                                  param_attr=attr)
        attr = {'shape': [-1, 4], 'name': string(node.layer_name + '_reshape2')}
        node.fluid_code.add_layer("reshape",
                                  inputs='pbv',
                                  output='pbv',
                                  param_attr=attr)
        # TODO(syf): need chaeck
        attr = {
            'shape': [-1, node.input_shape[1][1], 4],
            'name': string(node.layer_name + '_reshape3')
        }
        node.fluid_code.add_layer("reshape",
                                  inputs=mbox_loc,
                                  output='mbox_loc',
                                  param_attr=attr)
        attr = {
            'background_label': background_label,
            'nms_threshold': nms_threshold,
            'nms_top_k': top_k,
            'keep_top_k': keep_top_k,
            'score_threshold': confidence_threshold,
            'nms_eta': eta
        }
        inputs_str = get_input_name(mbox_conf_flatten) + ', mbox_loc, pb, pbv'
        node.fluid_code.add_layer("detection_output",
                                  inputs=inputs_str,
                                  output=node,
                                  param_attr=attr)

    def Flatten(self, noed):
        assert len(
            node.inputs
        ) == 1, 'The count of DetectionOutput node\'s input is not 1.'
        input = self.graph.get_bottom_node(node, idx=0, 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
        shape = node.output_shape[0]
        attr = {'shape': shape, 'name': string(node.layer_name)}
        node.fluid_code.add_layer("reshape",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def Normalize(self, node):
        assert len(
            node.inputs) == 1, 'The count of Normalize node\'s input is not 1.'
        input = self.graph.get_bottom_node(node, idx=0, 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
        params = node.layer.norm_param
        across_spatial = params.across_spatial
        channel_shared = params.channel_shared
        assert across_spatial == False, "Only support across_spatial == False for Normalize"
        attr = {'axis': 1, 'name': string(node.layer_name + '_l2')}
        node.fluid_code.add_layer("l2_normalize",
                                  inputs=input,
                                  output=node.layer_name + '_l2',
                                  param_attr=attr)
        input_name = self.get_input_name(input)
        data = node.data
S
SunAhong1993 已提交
1058 1059 1060
        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)
        data = self.adjust_parameters(node)
S
SunAhong1993 已提交
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
        self.weights[node.layer_name + '_scale'] = data[0]
        node.fluid_code.add_note(
            '{}_scale_attr = ParamAttr(name=\'{}\')'.format(
                node.layer_name, node.layer_name + '_scale'))
        attr = {
            'shape': [1] if channel_shared else [node.input_shape[0][1]],
            'dtype': '{}.dtype'.format(input_name),
            'attr': '{}_scale_attr'.format(node.layer_name),
            'name': string(node.layer_name + '_param')
        }
        node.fluid_code.add_layer("create_parameter",
                                  inputs=None,
                                  output=node.layer_name + '_scale_param',
                                  param_attr=attr)
        attr = {
            'axis': -1 if channel_shared else 1,
            'name': string(node.layer_name + '_mul')
        }
        node.fluid_code.add_layer("elementwise_mul",
                                  inputs=node.layer_name + '_l2, ' +
                                  node.layer_name + '_scale_param',
                                  output=node,
                                  param_attr=attr)

    def Permute(self, node):
        assert len(
            node.inputs) == 1, 'The count of Permute node\'s input is not 1.'
        input = self.graph.get_bottom_node(node, idx=0, 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
        params = node.layer.permute_param
        order = list(params.order)
        attr = {'order': order, 'name': string(node.layer_name)}
        node.fluid_code.add_layer("transpose",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def Power(self, node):
        assert len(
            node.inputs) == 1, 'The count of Permute node\'s input is not 1.'
        input = self.graph.get_bottom_node(node, idx=0, 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
        params = node.layer.power_param
        power = params.power
        scale = params.scale
        shift = params.shift
        attr = {
            'scale': scale,
            'bias': shift,
            'bias_after_scale': True,
            'name': string(node.layer_name + '_scale')
        }
        node.fluid_code.add_layer("scale",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)
        attr = {'factor': power, 'name': string(node.layer_name)}
        node.fluid_code.add_layer("pow",
                                  inputs=node,
                                  output=node,
                                  param_attr=attr)

    def PriorBox(self, node):
        assert len(
            node.inputs) == 2, 'The count of PriorBox node\'s input is not 2.'
        input1 = self.graph.get_bottom_node(node, idx=0, 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
        input2 = self.graph.get_bottom_node(node, idx=1, copy=True)
        if self.is_Scale(input2):
            tmp = self.graph.get_bottom_node(input2, idx=0, copy=True)
            if self.is_BN(tmp):
                input2 = tmp
        input_dict = {'input': input1, 'image': input2}
        params = node.layer.prior_box_param
        step = getattr(params, 'step', 0.0)
        offset = getattr(params, 'offset', 0.5)
        min_size = list(params.min_size)
        max_size = list(params.max_size)
        aspect_ratio = list(params.aspect_ratio)
        flip = getattr(params, 'flip', False)
        clip = getattr(params, 'clip', False)
        variance = list(getattr(params, 'variance', [0.1, 0.1, 0.2, 0.2]))
        steps = tuple(step) if type(step) is list or type(step) is tuple else (
            step, step)
        attr = {
            'min_sizes': min_size,
            'max_sizes': max_size,
            'aspect_ratios': aspect_ratio,
            'variance': variance,
            'flip': flip,
            'clip': clip,
            'step': steps,
            'offset': offset,
            'min_max_aspect_ratios_order': True,
            'name': string(node.layer_name)
        }
        node.fluid_code.add_layer("prior_box",
                                  inputs=input_dict,
                                  output='{}_box, {}_var'.format(
                                      node.layer_name, node.layer_name),
                                  param_attr=attr)
        attr = {
            'shape': [1, 1, -1],
        }
        node.fluid_code.add_layer("reshape",
                                  inputs='{}_box'.format(node.layer_name),
                                  output='{}_box'.format(node.layer_name),
                                  param_attr=attr)
        attr = {
            'shape': [1, 1, -1],
        }
        node.fluid_code.add_layer("reshape",
                                  inputs='{}_var'.format(node.layer_name),
                                  output='{}_var'.format(node.layer_name),
                                  param_attr=attr)
        attr = {'axis': 1, 'name': string(node.layer_name + '_concat')}
        node.fluid_code.add_layer("concat",
                                  inputs='[{}_box, {}_var]'.format(
                                      node.layer_name, node.layer_name),
                                  output=node,
                                  param_attr=attr)

    def Reduction(self, node):
        assert len(
            node.inputs) == 1, 'The count of Reduction node\'s input is not 1.'
        input = self.graph.get_bottom_node(node, idx=0, 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
        params = node.layer.reduction_param
        operation = params.operation
        axis = params.axis
        coeff = params.coeff
        assert operation >= 1 and operation <= 4, "reduction reduction [%s] error" % (
            operation)
        input_len = len(node.input_shape[0])
        if axis < 0:
            axis += input_len + 1
        dim = list(range(input_len))
        if operation == 1:  ## operation = SUM
            attr = {
                'dim': dim[axis:],
                'keep_dim': False,
                'name': string(node.layer_name)
            }
            node.fluid_code.add_layer("reduce_sum",
                                      inputs=input,
                                      output=node,
                                      param_attr=attr)
        elif operation == 2:  ## operation = ASUM
            attr = {'name': string(node.layer_name + '_abs')}
            node.fluid_code.add_layer("abs",
                                      inputs=input,
                                      output=node,
                                      param_attr=attr)
            attr = {
                'dim': dim[axis:],
                'keep_dim': False,
                'name': string(node.layer_name)
            }
            node.fluid_code.add_layer("reduce_sum",
                                      inputs=node,
                                      output=node,
                                      param_attr=attr)
        elif operation == 3:  ## operation = SUMSQ
            attr = {'factor': 2.0, 'name': string(node.layer_name + '_pow')}
            node.fluid_code.add_layer("pow",
                                      inputs=input,
                                      output=node,
                                      param_attr=attr)
            attr = {
                'dim': dim[axis:],
                'keep_dim': False,
                'name': string(node.layer_name)
            }
            node.fluid_code.add_layer("reduce_sum",
                                      inputs=node,
                                      output=node,
                                      param_attr=attr)
        else:  ## operation = MEAN
            attr = {
                'dim': dim[axis:],
                'keep_dim': False,
                'name': string(node.layer_name)
            }
            node.fluid_code.add_layer("reduce_mean",
                                      inputs=node,
                                      output=node,
                                      param_attr=attr)
        attr = {'scale': coeff}
        node.fluid_code.add_layer("scale",
                                  inputs=node,
                                  output=node,
                                  param_attr=attr)

    def ROIPooling(self, node):
        assert len(
            node.inputs) == 2, 'The count of ROIPooling node\'s input is not 2.'
        input1 = self.graph.get_bottom_node(node, idx=0, 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
        input2 = self.graph.get_bottom_node(node, idx=1, copy=True)
        if self.is_Scale(input2):
            tmp = self.graph.get_bottom_node(input2, idx=0, copy=True)
            if self.is_BN(tmp):
                input2 = tmp
        attr = {'axes': [1], 'starts': [1], 'ends': [5]}
        node.fluid_code.add_layer("slice",
                                  inputs=input2,
                                  output=input2,
                                  param_attr=attr)
        input_dict = {'input': input1, 'rois': input2}
        params = node.layer.roi_pooling_param
        attr = {
            'pooled_w': params.pooled_w,
            'pooled_h': params.pooled_h,
            'spatial_scale': params.spatial_scale,
            'name': string(node.layer_name)
        }
        node.fluid_code.add_layer("roi_pool",
                                  inputs=input_dict,
                                  output=node,
                                  param_attr=attr)

    def Select(self, node):
        assert len(
S
SunAhong1993 已提交
1299
            node.inputs) == 1, 'The count of Select node\'s input is not 1.'
S
SunAhong1993 已提交
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
        input = self.graph.get_bottom_node(node, idx=0, 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
        params = node.layer.select_param
        slice_point = list(params.slice_point)
        axis = params.axis
        maxint32 = 2147483647
        slice_point = [0] + slice_point
        slice_point.append(maxint32)
        i = 0
        node.fluid_code.add_note('{} = []'.format(node.layer_name))
        for i in range(len(slice_point)):
            attr = {
                'axes': [axis],
                'starts': [slice_point[i]],
                'ends': [slice_point[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(slice_point) - 2:
                break
S
SunAhong1993 已提交
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374

    def ShuffleChannel(self, node):
        assert len(node.inputs
                   ) == 1, 'The count of ShuffleChannel node\'s input is not 1.'
        params = node.layer.shuffle_channel_param
        group = params.group
        input = self.graph.get_bottom_node(node, idx=0, 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
        attr = {'group': group, 'name': string(node.layer_name)}
        node.fluid_code.add_layer("shuffle_channel",
                                  inputs=input,
                                  output=node,
                                  param_attr=attr)

    def deal_custom_layer(self, node):
        op = node.layer_type
        custom_code, func = make_custom_layer(node)
        params = get_params(node.layer, node.layer_type)
        arg_names, kwargs = set_args(func, params)
        kwargs['name'] = string(node.layer_name)
        kwargs['input_shape'] = node.input_shape
        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)
        data = self.adjust_parameters(node)
        weights_name = deal_weights(node)
        for i in range(len(data)):
            self.weights[weights_name[i]] = data[i]
        inputs_node = []
        for i in range(len(node.inputs)):
            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_node.append(input)
        node.fluid_code.add_layer(func.__code__.co_name,
                                  inputs=inputs_node,
                                  output=node,
                                  param_attr=kwargs,
                                  is_custom_layer=True)
        if op not in self.mylayers:
            self.mylayers[op] = custom_code