batchnorm2d_fuser.py 6.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#   Copyright (c) 2020  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.

import numpy as np
from x2paddle.optimizer.pattern_matcher import FuseBase
from x2paddle.core.program import PaddleGraph, PaddleLayer
from x2paddle.core.util import *


class BatchNorm2dFuser(FuseBase):
    def __init__(self):
        super(BatchNorm2dFuser, self).__init__(graph_type="dygraph")

    def build_pattern(self):
        """ 描述需要替换的batchnorm2d图结构。
        batchnorm2d层模式python实现代码示例:
S
SunAhong1993 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
            x336 = fluid.layers.shape(input=x334)
            x336 = len(x336)
            x337 = x336 != 4
            if x337 :
                raise RaiseException('Exception')
            if False :
                x351 = fluid.layers.shape(input=x334)
                x352 = x351[0]
                x353 = len(x351)
                x354 = x353 - 2
                x357 = x352
                for _x356 in range(x354):
                    x358 = _x356 + 2
                    x359 = x351[x358]
                    x360 = x357 * x359
                    x355 = x360
                x361 = x355 == 1
                if x361 :
                    raise RaiseException('Exception')
            x364 = self.batchnorm7(x334)
48 49 50 51 52 53
        """

        def gen_name(id):
            return "x" + str(id)

        self.pattern.add_layer(
S
SunAhong1993 已提交
54 55
            "fluid.layers.shape",
            inputs={'input': "bn-input-0"},
S
SunAhong1993 已提交
56
            outputs=[gen_name(0)])
57
        self.pattern.add_layer(
S
SunAhong1993 已提交
58
            "prim.len", inputs={'input': gen_name(0)}, outputs=[gen_name(0)])
59
        self.pattern.add_layer(
S
SunAhong1993 已提交
60 61
            "prim.ne", inputs={"x": gen_name(0)}, outputs=[gen_name(1)], y=4)
        self.pattern.add_layer("prim.if", {'input': gen_name(1)}, [gen_name(2)])
62 63 64 65
        if_layer1 = self.pattern.layers[list(self.pattern.layers.keys())[-1]]
        pattern_block0 = PaddleGraph(if_layer1, graph_type="dygraph")
        pattern_block0.add_layer(
            "prim.exception",
S
SunAhong1993 已提交
66 67 68
            inputs={},
            outputs=[gen_name(3)],
            input="Exception")
69 70 71
        if_layer1.add_block(pattern_block0)
        pattern_block1 = PaddleGraph(if_layer1, graph_type="dygraph")
        if_layer1.add_block(pattern_block1)
S
SunAhong1993 已提交
72
        self.pattern.add_layer("prim.if", {}, [gen_name(4)], input=False)
73 74 75
        if_layer2 = self.pattern.layers[list(self.pattern.layers.keys())[-1]]
        pattern_block0 = PaddleGraph(if_layer2, graph_type="dygraph")
        pattern_block0.add_layer(
S
SunAhong1993 已提交
76
            "fluid.layers.shape",
77
            inputs={'input': "bn-input-0"},
S
SunAhong1993 已提交
78
            outputs=[gen_name(5)])
79 80
        pattern_block0.add_layer(
            "prim.getitem",
S
SunAhong1993 已提交
81 82 83
            inputs={"list": gen_name(5)},
            outputs=[gen_name(6)],
            index=0)
84
        pattern_block0.add_layer(
S
SunAhong1993 已提交
85
            "prim.len", inputs={"input": gen_name(5)}, outputs=[gen_name(7)])
86
        pattern_block0.add_layer(
S
SunAhong1993 已提交
87
            "prim.sub", inputs={"x": gen_name(7)}, outputs=[gen_name(8)], y=2)
88
        pattern_block0.add_layer(
S
SunAhong1993 已提交
89
            "prim.equal", inputs={"input": gen_name(6)}, outputs=[gen_name(9)])
90 91
        pattern_block0.add_layer(
            "prim.loop",
S
SunAhong1993 已提交
92 93
            inputs={"input": gen_name(8)},
            outputs=[gen_name(8.1), gen_name(10)])
94 95 96 97
        loop_layer = pattern_block0.layers[list(pattern_block0.layers.keys())[
            -1]]
        pattern_block0_block0 = PaddleGraph(loop_layer, graph_type="dygraph")
        pattern_block0_block0.add_layer(
S
SunAhong1993 已提交
98
            "prim.add", inputs={"x": gen_name(10)}, outputs=[gen_name(11)], y=2)
99 100
        pattern_block0_block0.add_layer(
            "prim.getitem",
S
SunAhong1993 已提交
101 102 103
            inputs={"list": gen_name(5),
                    "index": gen_name(11)},
            outputs=[gen_name(12)])
104 105
        pattern_block0_block0.add_layer(
            "prim.mul",
S
SunAhong1993 已提交
106 107 108
            inputs={"x": gen_name(9),
                    "y": gen_name(12)},
            outputs=[gen_name(13)])
109 110
        pattern_block0_block0.add_layer(
            "prim.equal",
S
SunAhong1993 已提交
111 112 113 114
            inputs={"input": gen_name(13)},
            outputs=[gen_name(8.1)])
        loop_layer.inputs["input-1"] = gen_name(5)
        loop_layer.inputs["input-2"] = gen_name(9)
115 116
        loop_layer.add_block(pattern_block0_block0)
        pattern_block0.add_layer(
S
SunAhong1993 已提交
117
            "prim.eq", inputs={"x": gen_name(8.1)}, outputs=[gen_name(14)], y=1)
118
        pattern_block0.add_layer(
S
SunAhong1993 已提交
119 120
            "prim.if", inputs={"input": gen_name(14)}, outputs=[gen_name(15)])
        if_layer21 = pattern_block0.layers[list(pattern_block0.layers.keys())[
121
            -1]]
S
SunAhong1993 已提交
122
        pattern_block0_block0 = PaddleGraph(if_layer21, graph_type="dygraph")
123 124
        pattern_block0_block0.add_layer(
            "prim.exception",
S
SunAhong1993 已提交
125 126 127 128 129 130 131 132 133 134
            inputs={},
            outputs=[gen_name(15)],
            input="Exception")
        if_layer21.add_block(pattern_block0_block0)
        pattern_block0_block1 = PaddleGraph(if_layer21, graph_type="dygraph")
        if_layer21.add_block(pattern_block0_block1)
        if_layer2.add_block(pattern_block0)
        pattern_block1 = PaddleGraph(if_layer2, graph_type="dygraph")
        if_layer2.add_block(pattern_block1)
        if_layer2.inputs["input-0"] = "bn-input-0"
135
        self.pattern.add_layer(
S
SunAhong1993 已提交
136
            "paddle.nn.BatchNorm",
137
            inputs={"input": "bn-input-0"},
S
SunAhong1993 已提交
138
            outputs=[gen_name(16), gen_name(17)],
139 140 141 142
            is_test=True,
            num_channels=160,
            momentum=0.1,
            epsilon=0.001)
S
SunAhong1993 已提交
143
        self.pattern.build(inputs={"input-0": "bn-input-0"})
144 145 146 147 148 149 150

    def insert_new_layer(self, graph, parameters, matches):
        new_layer = self.gen_new_layer(parameters, matches)
        new_layer_id = list(matches.keys())[0]
        graph.layers[new_layer_id] = new_layer
        matches.pop(new_layer_id)

S
SunAhong1993 已提交
151 152 153 154
#         for layer in matches.values():
#             print(layer.outputs)
#         print("-------")

155 156 157 158
    def gen_new_layer(self, parameters, matches):
        layers_id = list(matches.keys())
        layer = matches[layers_id[-1]]
        return layer