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

# TODO useless node remove
J
jiangjiajun 已提交
16
from x2paddle.op_mapper.tf_op_mapper import TFOpMapper
J
jiangjiajun 已提交
17
from x2paddle.core.fluid_code import Layer
J
jiangjiajun 已提交
18
from x2paddle.core.util import *
J
jiangjiajun 已提交
19
import numpy
J
jiangjiajun 已提交
20
import copy as cp
J
jiangjiajun 已提交
21 22


J
jiangjiajun 已提交
23 24 25 26 27 28 29 30 31
def exist_act(node):
    for layer in node.fluid_code.layers:
        if layer.param_attr is not None:
            act = layer.param_attr.get("act", None)
            if act is not None:
                return True
    return False


J
jiangjiajun 已提交
32 33 34 35 36 37 38 39 40
class TFOptimizer(object):
    activation_ops = {
        'Relu': 'relu',
        'Sigmoid': 'sigmoid',
        'Relu6': 'relu6',
        'swish_f32': 'swish'
    }
    layers_with_act = [
        'Conv2D', 'BiasAdd', 'DepthwiseConv2dNative', 'Conv2DBackpropInput',
41 42
        'FusedBatchNorm', 'conv2d', 'elementwise_add', 'conv2d_transpose',
        'batch_norm'
J
jiangjiajun 已提交
43 44
    ]
    layers_with_bias = [
45 46
        'Conv2D', 'DepthwiseConv2dNative', 'Conv2DBackpropInput', 'conv2d',
        'conv2d_transpose'
J
jiangjiajun 已提交
47
    ]
48

J
jiangjiajun 已提交
49 50 51 52 53 54 55 56
    def __init__(self, op_mapper):
        self.op_mapper = op_mapper
        self.graph = op_mapper.graph

    def delete_redundance_code(self):
        for node_name in self.graph.topo_sort:
            if node_name in self.op_mapper.omit_nodes:
                node = self.graph.get_node(node_name)
J
jiangjiajun 已提交
57 58
                if node is None:
                    continue
J
jiangjiajun 已提交
59 60 61 62
                omit_freq = self.op_mapper.omit_nodes.count(node_name)
                if len(node.outputs) <= omit_freq:
                    node.fluid_code.clear()

J
jiangjiajun 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
                    # remove node from graph
                    input_names = node.inputs
                    output_names = node.outputs
                    for in_name in input_names:
                        in_node = self.graph.get_node(in_name)
                        index = in_node.outputs.index(node_name)
                        del in_node.outputs[index]
                    for out_name in output_names:
                        out_node = self.graph.get_node(out_name)
                        index = out_node.inputs.index(node_name)
                        del out_node.inputs[index]
                    del self.graph.node_map[node_name]

    def strip_graph(self):
        visited_nodes = set()

        def visit(node_name):
            if node_name in visited_nodes:
                return
            visited_nodes.add(node_name)
            input_names = self.graph.get_node(node_name).inputs
            for in_name in input_names:
                visit(in_name)

        for node_name in self.graph.output_nodes:
            visit(node_name)

        for i, node_name in enumerate(self.graph.topo_sort):
            if node_name not in visited_nodes:
                node = self.graph.get_node(node_name)
                if node is None:
                    continue
                input_names = node.inputs
                output_names = node.outputs
                for in_name in input_names:
                    in_node = self.graph.get_node(in_name)
                    index = in_node.outputs.index(node_name)
                    del in_node.outputs[index]
                for out_name in output_names:
                    out_node = self.graph.get_node(out_name)
                    index = out_node.inputs.index(node_name)
                    del out_node.inputs[index]
                del self.graph.node_map[node_name]

J
jiangjiajun 已提交
107 108 109 110
    def merge_activation(self):
        act_nodes = list()
        for node_name in self.graph.topo_sort:
            node = self.graph.get_node(node_name)
J
jiangjiajun 已提交
111 112
            if node is None:
                continue
J
jiangjiajun 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
            if node.layer_type in self.activation_ops:
                act_nodes.append(node_name)

        for act_node_name in act_nodes:
            node = self.graph.get_node(act_node_name)
            input = self.graph.get_node(node.inputs[0])
            if input.layer_type not in self.layers_with_act:
                continue
            if len(input.fluid_code.layers) == 0:
                continue
            if 'act' in input.fluid_code.layers[
                    -1].param_attr and input.fluid_code.layers[-1].param_attr[
                        'act'] is not None:
                continue
            if len(input.outputs) != 1:
                continue
129 130 131 132 133 134
            index = -1
            for i in range(len(input.fluid_code.layers)):
                if input.fluid_code.layers[i].op in self.layers_with_act:
                    index = i
                    break
            input.fluid_code.layers[index].param_attr['act'] = string(
J
jiangjiajun 已提交
135 136 137 138 139 140 141 142
                self.activation_ops[node.layer_type])
            input.fluid_code.layers[-1].output = node.fluid_code.layers[
                0].output
            self.graph.remove_node(act_node_name)

    def merge_bias(self):
        for node_name in self.graph.topo_sort:
            node = self.graph.get_node(node_name)
J
jiangjiajun 已提交
143 144
            if node is None:
                continue
J
jiangjiajun 已提交
145 146 147 148 149 150 151 152 153 154 155 156
            if node.layer_type == "BiasAdd":
                input = self.graph.get_node(node.inputs[0])
                if input.layer_type not in self.layers_with_bias:
                    continue
                if len(input.outputs) != 1:
                    continue
                if len(input.fluid_code.layers) == 0:
                    continue
                bias_with_act = False
                if 'act' in node.fluid_code.layers[-1].param_attr:
                    bias_with_act = True
                layer_with_act = False
157 158 159 160 161
                index = -1
                for i in range(len(input.fluid_code.layers)):
                    if input.fluid_code.layers[i].op in self.layers_with_bias:
                        index = i
                        break
J
jiangjiajun 已提交
162
                if 'act' in input.fluid_code.layers[
163 164
                        index].param_attr and input.fluid_code.layers[
                            index].param_attr['act'] is not None:
J
jiangjiajun 已提交
165 166 167 168
                    layer_with_act = True

                if bias_with_act and layer_with_act:
                    continue
169
                if not input.fluid_code.layers[index].param_attr['bias_attr']:
J
jiangjiajun 已提交
170
                    bias_name = node.inputs[1]
171
                    input.fluid_code.layers[index].param_attr[
J
jiangjiajun 已提交
172 173 174 175
                        'bias_attr'] = string(bias_name)
                    input.fluid_code.layers[-1].output = node.fluid_code.layers[
                        0].output
                    if bias_with_act:
176
                        input.fluid_code.layers[index].param_attr[
J
jiangjiajun 已提交
177 178 179
                            'act'] = node.fluid_code.layers[-1].param_attr[
                                'act']
                    node.fluid_code.clear()
180 181 182
                    self.graph.remove_node(node.layer_name)

    def remove_transpose(self):
J
jiangjiajun 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
        graph_copy = cp.deepcopy(self.graph)
        nhwc_insensitive_ops = [
            'Relu', 'Relu6', 'Abs', 'Sigmoid', 'Exp', 'Rsqrt', 'swish_f32',
            'LeakyRelu', 'Cast'
        ]
        elementwise_ops = [
            'Sub', 'Add', 'RealDiv', 'Maximum', 'Mul', 'FloorDiv',
            'GreaterEqual'
        ]
        for node_name in self.graph.topo_sort:
            node = graph_copy.get_node(node_name)
            if node is None:
                continue
            if node.layer_type in nhwc_insensitive_ops:
                graph_copy.remove_node(node_name)

199 200 201
        optimize_ops = [
            'Conv2D', 'MaxPool', 'FusedBatchNorm', 'DepthwiseConv2dNative',
            'AvgPool', 'Pad', 'Conv2DBackpropInput', 'ResizeNearestNeighbor',
J
jiangjiajun 已提交
202
            'ResizeBilinear', "Placeholder"
203
        ]
J
jiangjiajun 已提交
204

205
        for node_name in self.graph.topo_sort:
J
jiangjiajun 已提交
206
            node = graph_copy.get_node(node_name)
207 208
            if node is None:
                continue
J
jiangjiajun 已提交
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
            if node.layer_type in elementwise_ops:
                is_nhwc = True
                for in_name in node.inputs:
                    in_node = graph_copy.get_node(in_name)
                    if hasattr(in_node, "is_nhwc"):
                        if not in_node.is_nhwc:
                            is_nhwc = False
                    else:
                        if len(in_node.fluid_code.layers) < 2:
                            is_nhwc = False
                            continue
                        if in_node.fluid_code.layers[
                                -1].op != "transpose" or in_node.fluid_code.layers[
                                    -1].param_attr["perm"] != [0, 2, 3, 1]:
                            is_nhwc = False
                            continue
                node.is_nhwc = is_nhwc

        for i in range(len(self.graph.topo_sort)):
            node_name = self.graph.topo_sort[-1 * i - 1]
            node = graph_copy.get_node(node_name)
            if node is None:
231
                continue
J
jiangjiajun 已提交
232 233 234
            if node.layer_type in elementwise_ops:
                can_be_removed = True
                if len(node.fluid_code.layers) > 1:
235
                    can_be_removed = False
J
jiangjiajun 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
                if not node.is_nhwc:
                    can_be_removed = False
                for out_name in node.outputs:
                    out_node = graph_copy.get_node(out_name)
                    if hasattr(out_node, "is_nhwc"):
                        if not out_node.is_nhwc:
                            can_be_removed = False
                    else:
                        if len(out_node.fluid_code.layers) < 2:
                            can_be_removed = False
                            break
                        if out_node.fluid_code.layers[
                                0].op != "transpose" or out_node.fluid_code.layers[
                                    0].param_attr["perm"] != [0, 3, 1, 2]:
                            can_be_removed = False
                            break
                node.can_be_removed = can_be_removed
253

J
jiangjiajun 已提交
254 255 256 257 258 259 260 261 262 263 264
        for node_name in self.graph.topo_sort:
            node = graph_copy.get_node(node_name)
            if node is None:
                continue
            if node.layer_type in optimize_ops:
                if node.fluid_code.layers[
                        -1].op != "transpose" or node.fluid_code.layers[
                            -1].param_attr["perm"] != [0, 2, 3, 1]:
                    continue
                can_be_removed = True
                output_names = node.outputs
265
                for out_name in output_names:
J
jiangjiajun 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
                    out_node = graph_copy.get_node(out_name)
                    if hasattr(out_node, "can_be_removed"):
                        if not out_node.can_be_removed:
                            can_be_removed = False
                            break
                    elif out_node.fluid_code.layers[
                            0].op != "transpose" or out_node.fluid_code.layers[
                                0].param_attr["perm"] != [0, 3, 1, 2]:
                        can_be_removed = False
                        break
                if can_be_removed and len(node.fluid_code.layers) > 1:
                    true_node = self.graph.get_node(node_name)
                    if true_node.layer_type == "Placeholder":
                        index = self.graph.input_nodes.index(
                            true_node.fluid_code.layers[-2].output)
                        if isinstance(true_node.fluid_code.layers[-1].output,
                                      str):
                            self.graph.input_nodes[
                                index] = true_node.fluid_code.layers[-1].output
                        else:
                            self.graph.input_nodes[
                                index] = true_node.fluid_code.layers[
                                    -1].output.layer_name
                    true_node.fluid_code.layers[
                        -2].output = true_node.fluid_code.layers[-1].output
                    node.removed = True
                    del true_node.fluid_code.layers[-1]
                    for out_name in output_names:
                        out_node = self.graph.get_node(out_name)
                        if out_node.layer_type in elementwise_ops:
                            continue
                        out_node.fluid_code.layers[
                            1].inputs = out_node.fluid_code.layers[0].inputs
299
                        del out_node.fluid_code.layers[0]
J
jiangjiajun 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363

        for node_name in self.graph.topo_sort:
            node = graph_copy.get_node(node_name)
            if node is None:
                continue
            if node.layer_type in elementwise_ops:
                if not node.can_be_removed:
                    true_node = self.graph.get_node(node_name)
                    for i, in_name in enumerate(node.inputs):
                        in_node = graph_copy.get_node(in_name)
                        if hasattr(in_node, "is_nhwc") and in_node.is_nhwc:
                            if i == 0:
                                l = Layer()
                                l.op = "transpose"
                                l.inputs = true_node.fluid_code.layers[
                                    0].inputs["x"]
                                l.param_attr = {"perm": [0, 2, 3, 1]}
                                l.output = "nhwc_" + l.inputs.layer_name
                                true_node.fluid_code.layers[0].inputs[
                                    "x"] = l.output
                                true_node.fluid_code.layers.insert(0, l)
                            elif i == 1:
                                l = Layer()
                                l.op = "transpose"
                                l.inputs = true_node.fluid_code.layers[
                                    0].inputs["y"]
                                l.param_attr = {"perm": [0, 2, 3, 1]}
                                l.output = "nhwc_" + l.inputs.layer_name
                                true_node.fluid_code.layers[0].inputs[
                                    "y"] = l.output
                                true_node.fluid_code.layers.insert(0, l)
                            else:
                                raise Exception("Unexpected situation happend")
                    continue
                else:
                    for out_name in node.outputs:
                        out_node = self.graph.get_node(out_name)
                        if out_node.layer_type not in elementwise_ops:
                            assert out_node.fluid_code.layers[
                                0].op == "transpose", "unexpected situation happend"
                            out_node.fluid_code.layers[
                                1].inputs = out_node.fluid_code.layers[0].inputs
                            del out_node.fluid_code.layers[0]

    def make_nchw_input_output(self):
        for i, name in enumerate(self.graph.input_nodes):
            node = self.graph.get_node(name)
            if len(node.out_shapes[0]) == 4 and node.tf_data_format == "NHWC":
                shape = node.fluid_code.layers[0].param_attr["shape"]
                shape = [shape[i] for i in [0, 3, 1, 2]]
                node.fluid_code.layers[0].param_attr["shape"] = shape
                node.fluid_code.layers[0].output = "nhwc_" + name
                attr = {"perm": [0, 2, 3, 1]}
                node.fluid_code.add_layer("transpose",
                                          inputs="nhwc_" + name,
                                          output=node,
                                          param_attr=attr)
                self.graph.input_nodes[i] = "nhwc_" + name
        for i, name in enumerate(self.graph.output_nodes):
            node = self.graph.get_node(name)
            if node.layer_type != "transpose":
                if node.fluid_code.layers[-1].op == "transpose":
                    node.fluid_code.layers[-2].output = name
                    del node.fluid_code.layers[-1]
J
jiangjiajun 已提交
364

J
jiangjiajun 已提交
365 366 367
    def optimize_sub_graph(self):
        self.merge_batch_norm()
        self.merge_prelu()
J
jiangjiajun 已提交
368 369
        self.merge_scale()
        self.merge_affine_channel()
J
jiangjiajun 已提交
370

J
jiangjiajun 已提交
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
    def merge_batch_norm(self):
        for i, name in enumerate(self.graph.topo_sort):
            node = self.graph.get_node(name)
            if node is None:
                continue
            is_batch_norm = True
            if node.layer_type == "Add":
                in_nodes0 = [
                    self.graph.get_node(in_name) for in_name in node.inputs
                ]
                if in_nodes0[0].layer_type != "Mul" or in_nodes0[
                        1].layer_type != "Sub":
                    is_batch_norm = False
                    continue

J
jiangjiajun 已提交
386 387 388 389
                if exist_act(in_nodes0[0]) or exist_act(in_nodes0[1]):
                    is_batch_norm = False
                    continue

J
jiangjiajun 已提交
390 391 392 393 394 395 396 397 398 399 400 401 402 403
                in_nodes1 = [
                    self.graph.get_node(in_name)
                    for in_name in in_nodes0[0].inputs
                ]
                in_nodes2 = [
                    self.graph.get_node(in_name)
                    for in_name in in_nodes0[1].inputs
                ]
                if len(in_nodes1[0].out_shapes[0]) != 4:
                    is_batch_norm = False
                    continue
                if in_nodes1[1].layer_type != "Mul":
                    is_batch_norm = False
                    continue
J
jiangjiajun 已提交
404 405 406
                if exist_act(in_nodes1[1]):
                    is_batch_norm = False
                    continue
J
jiangjiajun 已提交
407 408 409 410 411

                if in_nodes2[0].layer_type != "Const" or in_nodes2[
                        1].layer_type != "Mul":
                    is_batch_norm = False
                    continue
J
jiangjiajun 已提交
412 413 414
                if exist_act(in_nodes2[1]):
                    is_batch_norm = False
                    continue
J
jiangjiajun 已提交
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437

                in_nodes3 = [
                    self.graph.get_node(in_name)
                    for in_name in in_nodes1[1].inputs
                ]
                if in_nodes3[0].layer_type != "Rsqrt" or in_nodes3[
                        1].layer_type != "Const":
                    is_batch_norm = False
                    continue

                in_nodes4 = [
                    self.graph.get_node(in_name)
                    for in_name in in_nodes2[1].inputs
                ]
                if in_nodes4[0].layer_type != "Const" or in_nodes4[
                        1].layer_name != in_nodes1[1].layer_name:
                    is_batch_norm = False
                    continue

                in_nodes5 = self.graph.get_node(in_nodes3[0].inputs[0])
                if in_nodes5.layer_type != "Add":
                    is_batch_norm = False
                    continue
J
jiangjiajun 已提交
438 439 440
                if exist_act(in_nodes5):
                    is_batch_norm = False
                    continue
J
jiangjiajun 已提交
441 442 443 444 445 446 447 448 449

                in_nodes6 = [
                    self.graph.get_node(in_name) for in_name in in_nodes5.inputs
                ]
                if in_nodes6[0].layer_type != "Const" or in_nodes6[
                        1].layer_type != "Const":
                    is_batch_norm = False
                    continue

J
jiangjiajun 已提交
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
                if len(in_nodes0[0].outputs) != 1:
                    is_batch_norm = False
                    continue
                if len(in_nodes0[1].outputs) != 1:
                    is_batch_norm = False
                    continue
                if len(in_nodes1[1].outputs) != 2:
                    is_batch_norm = False
                    continue
                if len(in_nodes2[0].outputs) != 1:
                    is_batch_norm = False
                    continue
                if len(in_nodes2[1].outputs) != 1:
                    is_batch_norm = False
                    continue
                if len(in_nodes3[0].outputs) != 1:
                    is_batch_norm = False
                    continue
                if len(in_nodes3[1].outputs) != 1:
                    is_batch_norm = False
                    continue
                if len(in_nodes4[0].outputs) != 1:
                    is_batch_norm = False
                    continue
                if len(in_nodes5.outputs) != 1:
                    is_batch_norm = False
                    continue
                if len(in_nodes6[0].outputs) != 1:
                    is_batch_norm = False
                    continue
                if len(in_nodes6[1].outputs) != 1:
                    is_batch_norm = False
                    continue

J
jiangjiajun 已提交
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
                conv_shape = in_nodes1[0].out_shapes[0]
                if conv_shape[3] < 0:
                    is_batch_norm = False
                    continue

                # moving_variance
                if in_nodes6[0].value.size != conv_shape[3]:
                    is_batch_norm = False
                    continue

                # epsilon
                if in_nodes6[1].value.size != 1:
                    is_batch_norm = False
                    continue

                # gamma
                if in_nodes3[1].value.size != conv_shape[3]:
                    is_batch_norm = False
                    continue

                # moving_mean
                if in_nodes4[0].value.size != conv_shape[3]:
                    is_batch_norm = False
                    continue

                # beta
                if in_nodes2[0].value.size != conv_shape[3]:
                    is_batch_norm = False
                    continue

                if is_batch_norm:
                    index = in_nodes1[0].outputs.index(in_nodes0[0].layer_name)
J
jiangjiajun 已提交
516
                    in_nodes1[0].outputs[index] = node.layer_name
J
jiangjiajun 已提交
517 518 519 520 521 522 523 524 525 526 527 528 529 530
                    node.layer_type = "FusedBatchNorm"
                    node.inputs = [in_nodes1[0].layer_name]
                    act = node.fluid_code.layers[-1].param_attr.get("act", None)
                    node.fluid_code.clear()
                    attr = {
                        "epsilon": in_nodes6[1].value,
                        "param_attr": string(in_nodes3[1].layer_name),
                        "bias_attr": string(in_nodes2[0].layer_name),
                        "moving_mean_name": string(in_nodes4[0].layer_name),
                        "moving_variance_name": string(in_nodes6[0].layer_name),
                        "is_test": True,
                        "act": act
                    }

J
jiangjiajun 已提交
531 532 533 534 535
                    node.fluid_code.add_layer(
                        "batch_norm",
                        inputs=in_nodes1[0].fluid_code.layers[-1].output,
                        output=node,
                        param_attr=attr)
J
jiangjiajun 已提交
536 537 538 539 540 541 542 543

                del self.graph.node_map[in_nodes0[0].layer_name]
                del self.graph.node_map[in_nodes0[1].layer_name]
                del self.graph.node_map[in_nodes1[1].layer_name]
                del self.graph.node_map[in_nodes2[1].layer_name]
                del self.graph.node_map[in_nodes3[0].layer_name]
                del self.graph.node_map[in_nodes4[0].layer_name]
                del self.graph.node_map[in_nodes5.layer_name]
J
jiangjiajun 已提交
544 545 546 547 548 549 550 551

    def merge_prelu(self):
        for i, name in enumerate(self.graph.topo_sort):
            node = self.graph.get_node(name)
            if node is None:
                continue
            is_prelu = True
            if node.layer_type == "Add":
J
jiangjiajun 已提交
552 553 554
                if exist_act(node):
                    is_prelu = False
                    continue
J
jiangjiajun 已提交
555 556 557 558 559 560 561
                in_nodes0 = [
                    self.graph.get_node(in_name) for in_name in node.inputs
                ]
                if in_nodes0[0].layer_type != "Relu" or in_nodes0[
                        1].layer_type != "Mul":
                    is_prelu = False
                    continue
J
jiangjiajun 已提交
562 563 564 565
                if exist_act(in_nodes0[1]):
                    is_prelu = False
                    continue

J
jiangjiajun 已提交
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
                if len(in_nodes0[0].outputs) != 1 or len(
                        in_nodes0[1].outputs) != 1:
                    is_prelu = False
                    continue

                in_nodes1 = self.graph.get_node(in_nodes0[0].inputs[0])
                in_nodes2 = [
                    self.graph.get_node(in_name)
                    for in_name in in_nodes0[1].inputs
                ]
                if in_nodes2[1].layer_type != "Const" or numpy.fabs(
                        in_nodes2[1].value - 0.5) > 1e-06:
                    is_prelu = False
                    continue
                if in_nodes2[0].layer_type != "Mul":
                    is_prelu = False
                    continue
J
jiangjiajun 已提交
583 584 585
                if exist_act(in_nodes2[0]):
                    is_prelu = False
                    continue
J
jiangjiajun 已提交
586 587 588 589 590 591 592 593 594 595 596 597 598
                if len(in_nodes2[1].outputs) != 1 or len(
                        in_nodes2[0].outputs) != 1:
                    is_prelu = False
                    continue

                in_nodes3 = [
                    self.graph.get_node(in_name)
                    for in_name in in_nodes2[0].inputs
                ]
                if in_nodes3[0].layer_type != "Const" or in_nodes3[
                        1].layer_type != "Sub":
                    is_prelu = False
                    continue
J
jiangjiajun 已提交
599 600 601
                if exist_act(in_nodes3[1]):
                    is_prelu = False
                    continue
J
jiangjiajun 已提交
602 603 604 605 606 607 608 609 610 611 612 613 614 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 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
                if len(in_nodes3[0].outputs) != 1 or len(
                        in_nodes3[1].outputs) != 1:
                    is_prelu = False
                    continue

                in_nodes4 = [
                    self.graph.get_node(in_name)
                    for in_name in in_nodes3[1].inputs
                ]
                if in_nodes4[0].layer_name != in_nodes1.layer_name or in_nodes4[
                        1].layer_type != "Abs":
                    is_prelu = False
                    continue
                if len(in_nodes4[1].outputs) != 1:
                    is_prelu = False
                    continue

                in_nodes5 = self.graph.get_node(in_nodes4[1].inputs[0])
                if in_nodes5.layer_name != in_nodes1.layer_name:
                    is_prelu = False
                    continue

                if len(in_nodes0[0].outputs) != 1:
                    is_prelu = false
                    continue
                if len(in_nodes0[1].outputs) != 1:
                    is_prelu = False
                    continue
                if len(in_nodes1.outputs) < 3:
                    is_prelu = False
                    continue
                if len(in_nodes2[0].outputs) != 1:
                    is_prelu = false
                    continue
                if len(in_nodes2[1].outputs) != 1:
                    is_prelu = False
                    continue
                if len(in_nodes3[0].outputs) != 1:
                    is_prelu = False
                    continue
                if len(in_nodes3[1].outputs) != 1:
                    is_prelu = false
                    continue
                if len(in_nodes4[1].outputs) != 1:
                    is_prelu = False
                    continue

                mode = None
                in_shape = in_nodes1.out_shapes[0]
                if in_shape == list(in_nodes3[0].value.shape):
                    mode = "element"
                elif len(in_nodes3[0].value.shape) == 0:
                    mode = "all"
                elif len(in_nodes3[0].value.shape
                         ) == 1 and in_nodes3[0].value.shape[0] == 1:
                    mode = "all"
                elif len(in_shape) == 4 and len(
                        in_nodes3[0].value.shape
                ) == 1 and in_nodes3[0].value.shape[0] == in_shape[-1]:
                    mode = "channel"
                    weight = self.op_mapper.weights[in_nodes3[0].layer_name]
                    weight = numpy.expand_dims(weight, 0)
                    weight = numpy.expand_dims(weight, 2)
                    weight = numpy.expand_dims(weight, 3)
                    self.op_mapper.weights[in_nodes3[0].layer_name] = weight
                    in_nodes3[0].fluid_code.layers[0].param_attr["shape"] = [
                        1, in_shape[-1], 1, 1
                    ]
                else:
                    is_prelu = False
                    continue

                if is_prelu:
                    index = in_nodes1.outputs.index(in_nodes0[0].layer_name)
                    del in_nodes1.outputs[index]
                    index = in_nodes1.outputs.index(in_nodes3[1].layer_name)
                    del in_nodes1.outputs[index]
                    index = in_nodes1.outputs.index(in_nodes4[1].layer_name)
                    del in_nodes1.outputs[index]
J
jiangjiajun 已提交
681
                    in_nodes1.outputs.append(node.layer_name)
J
jiangjiajun 已提交
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702

                    node.layer_type = "Prelu"
                    node.inputs = [in_nodes1.layer_name]
                    act = node.fluid_code.layers[-1].param_attr.get("act", None)
                    node.fluid_code.clear()
                    attr = {
                        "mode": string(mode),
                        "param_attr": string(in_nodes3[0].layer_name)
                    }

                    node.fluid_code.add_layer(
                        "prelu",
                        inputs=in_nodes1.fluid_code.layers[-1].output,
                        output=node,
                        param_attr=attr)
                del self.graph.node_map[in_nodes0[0].layer_name]
                del self.graph.node_map[in_nodes0[1].layer_name]
                del self.graph.node_map[in_nodes2[0].layer_name]
                del self.graph.node_map[in_nodes2[1].layer_name]
                del self.graph.node_map[in_nodes3[1].layer_name]
                del self.graph.node_map[in_nodes4[1].layer_name]
J
jiangjiajun 已提交
703

J
jiangjiajun 已提交
704
    def merge_scale(self):
J
jiangjiajun 已提交
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 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
        for i, name in enumerate(self.graph.topo_sort):
            node = self.graph.get_node(name)
            if node is None:
                continue
            is_scale = True
            if node.layer_type == "Sub":
                in_nodes0 = [
                    self.graph.get_node(in_name) for in_name in node.inputs
                ]
                if in_nodes0[0].layer_type != "Mul" or in_nodes0[
                        1].layer_type != "Const" or in_nodes0[1].value.size != 1:
                    is_scale = False
                    continue
                if exist_act(in_nodes0[0]):
                    is_scale = False
                    continue
                if len(in_nodes0[0].outputs) != 1 or len(
                        in_nodes0[1].outputs) != 1:
                    is_scale = False
                    continue

                in_nodes1 = [
                    self.graph.get_node(in_name)
                    for in_name in in_nodes0[0].inputs
                ]
                if in_nodes1[0].layer_type != "Const" or in_nodes1[
                        1].layer_type != "RealDiv" or in_nodes1[
                            0].value.size != 1:
                    is_scale = False
                    continue
                if exist_act(in_nodes1[1]):
                    is_scale = False
                    continue
                if len(in_nodes1[0].outputs) != 1 or len(
                        in_nodes1[1].outputs) != 1:
                    is_scale = False
                    continue

                in_nodes2 = [
                    self.graph.get_node(in_name)
                    for in_name in in_nodes1[1].inputs
                ]
                if in_nodes2[1].layer_type != "Const" or in_nodes2[
                        1].value.size != 1:
                    is_scale = False
                    continue

                if is_scale:
                    in_node = self.graph.get_node(in_nodes1[1].inputs[0])
                    index = in_node.outputs.index(in_nodes1[1].layer_name)
                    in_node.outputs[index] = node.layer_name
                    node.layer_type = "Scale"
                    node.inputs = [in_node.layer_name]
                    scale = 1.0 / in_nodes2[1].value * in_nodes1[0].value
                    act = None
                    if node.fluid_code.layers[0].param_attr is not None:
                        act = node.fluid_code.layers[0].param_attr.get(
                            "act", None)
                    node.fluid_code.clear()

                    attr = {
                        "scale": scale,
                        "bias": in_nodes0[1].value,
                        "bias_after_scale": True,
                        "act": act
                    }
                    node.fluid_code.add_layer("scale",
                                              inputs=in_node,
                                              output=node,
                                              param_attr=attr)

                    del self.graph.node_map[in_nodes0[0].layer_name]
                    del self.graph.node_map[in_nodes0[1].layer_name]
                    del self.graph.node_map[in_nodes1[0].layer_name]
                    del self.graph.node_map[in_nodes1[1].layer_name]
                    del self.graph.node_map[in_nodes2[1].layer_name]
J
jiangjiajun 已提交
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 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

    def merge_affine_channel(self):
        for i, name in enumerate(self.graph.topo_sort):
            node = self.graph.get_node(name)
            if node is None:
                continue
            is_affine_channel = True
            if node.layer_type == "RealDiv":
                in_nodes0 = [
                    self.graph.get_node(in_name) for in_name in node.inputs
                ]
                bias_add = True
                if (in_nodes0[0].layer_type != "Sub" and in_nodes0[0].layer_type
                        != "Add") or in_nodes0[1].layer_type != "Const" or len(
                            in_nodes0[1].value.shape) != 3:
                    is_affine_channel = False
                    continue
                if in_nodes0[0].layer_type == "Sub":
                    bias_add = False
                if exist_act(in_nodes0[0]):
                    is_affine_channel = False
                    continue
                if len(in_nodes0[0].outputs) != 1 or len(
                        in_nodes0[1].outputs) != 1:
                    is_affine_channel = False
                    continue
                in_nodes1 = [
                    self.graph.get_node(in_name)
                    for in_name in in_nodes0[0].inputs
                ]
                if len(in_nodes1[0].out_shapes[0]
                       ) != 4 or in_nodes1[1].layer_type != "Const" or len(
                           in_nodes1[1].value.shape) != 3:
                    is_affine_channel = False
                    continue
                if len(in_nodes1[1].outputs) != 1:
                    is_affine_channel = False
                    continue
                channel = in_nodes1[0].out_shapes[0][-1]
                if channel < 0 or channel != in_nodes0[
                        1].value.size or channel != in_nodes1[1].value.size:
                    is_affine_channel = False
                    continue
                if in_nodes0[1].out_shapes[0][-1] != in_nodes0[
                        1].value.size or in_nodes1[1].out_shapes[0][
                            -1] != in_nodes1[1].value.size:
                    is_affine_channel = False
                    continue
                if is_affine_channel:
                    in_node = in_nodes1[0]
                    index = in_node.outputs.index(in_nodes0[0].layer_name)
                    in_node.outputs[index] = node.layer_name
                    node.layer_type = "AffineChannel"
                    node.inputs = [in_node.layer_name]
                    scale = 1.0 / in_nodes0[1].value.flatten()
                    bias = in_nodes1[1].value.flatten(
                    ) / in_nodes0[1].value.flatten()
                    if not bias_add:
                        bias *= -1.0
                    self.op_mapper.weights[node.layer_name + "_scale"] = scale
                    self.op_mapper.weights[node.layer_name + "_bias"] = bias

                    act = None
                    if node.fluid_code.layers[0].param_attr is not None:
                        act = node.fluid_code.layers[0].param_attr.get(
                            "act", None)
                    node.fluid_code.clear()

                    attr = {
                        "dtype": string(scale.dtype),
                        "shape": [channel],
                        "name": string(node.layer_name + "_scale")
                    }
                    node.fluid_code.add_layer("create_parameter",
                                              inputs=None,
                                              output=node.layer_name + "_scale",
                                              param_attr=attr)
                    attr = {
                        "dtype": string(scale.dtype),
                        "shape": [channel],
                        "name": string(node.layer_name + "_bias")
                    }
                    node.fluid_code.add_layer("create_parameter",
                                              inputs=None,
                                              output=node.layer_name + "_bias",
                                              param_attr=attr)
                    inputs = {
                        "x": in_node,
                        "scale": node.layer_name + "_scale",
                        "bias": node.layer_name + "_bias"
                    }
                    attr = {"act": act}
                    node.fluid_code.add_layer("affine_channel",
                                              inputs=inputs,
                                              output=node,
                                              param_attr=attr)

                    del self.graph.node_map[in_nodes0[0].layer_name]
                    del self.graph.node_map[in_nodes0[1].layer_name]
                    del self.graph.node_map[in_nodes1[1].layer_name]