tf_batchnorm_fuser.py 8.6 KB
Newer Older
S
SunAhong1993 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#   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 copy
import numpy as np
from collections import OrderedDict
from x2paddle.optimizer.pattern_matcher import FuseBase
from x2paddle.core.program import PaddleGraph, PaddleLayer
from x2paddle.core.util import *


S
renam  
SunAhong1993 已提交
23
class DygraphTFBatchNormFuser(FuseBase):
S
SunAhong1993 已提交
24 25
    def __init__(self):
        self.bn_index = 0
S
renam  
SunAhong1993 已提交
26
        super(DygraphTFBatchNormFuser, self).__init__(graph_type="dygraph")
S
SunAhong1993 已提交
27
        self.patterns = list()
S
SunAhong1993 已提交
28 29 30 31 32 33 34 35 36 37

    def build_pattern(self):
        """ 描述需要替换的batchnorm图结构。
        batchnorm层模式python实现代码示例:
            
        """

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

S
SunAhong1993 已提交
38 39
        pattern = PaddleGraph(graph_type="dygraph")
        pattern.add_layer(
S
SunAhong1993 已提交
40 41 42
            "self.create_parameter",
            inputs={},
            outputs=[gen_name(0)])
S
SunAhong1993 已提交
43
        pattern.add_layer(
S
SunAhong1993 已提交
44 45 46 47
            "paddle.full",
            inputs={},
            outputs=[gen_name(1)],
            shape=[1])
S
SunAhong1993 已提交
48
        pattern.add_layer(
S
SunAhong1993 已提交
49 50 51
            "paddle.add",
            inputs={"x": gen_name(0), "y": gen_name(1)},
            outputs=[gen_name(2)])
S
SunAhong1993 已提交
52
        pattern.add_layer(
S
SunAhong1993 已提交
53 54 55
            "paddle.rsqrt",
            inputs={"x": gen_name(2)},
            outputs=[gen_name(3)])
S
SunAhong1993 已提交
56
        pattern.add_layer(
S
SunAhong1993 已提交
57 58 59
            "self.create_parameter",
            inputs={},
            outputs=[gen_name(4)])
S
SunAhong1993 已提交
60
        pattern.add_layer(
S
SunAhong1993 已提交
61 62 63
            "paddle.multiply",
            inputs={"x": gen_name(3), "y": gen_name(4)},
            outputs=[gen_name(5)])
S
SunAhong1993 已提交
64
        pattern.add_layer(
S
SunAhong1993 已提交
65 66 67
            "self.create_parameter",
            inputs={},
            outputs=[gen_name(6)])
S
SunAhong1993 已提交
68
        pattern.add_layer(
S
SunAhong1993 已提交
69 70 71
            "paddle.multiply",
            inputs={"x": gen_name(6), "y": gen_name(5)},
            outputs=[gen_name(7)])
S
SunAhong1993 已提交
72
        pattern.add_layer(
S
SunAhong1993 已提交
73 74 75
            "self.create_parameter",
            inputs={},
            outputs=[gen_name(8)])
S
SunAhong1993 已提交
76
        pattern.add_layer(
S
SunAhong1993 已提交
77
            "paddle.subtract",
S
SunAhong1993 已提交
78 79
            inputs={"x": gen_name(8), "y": gen_name(7)},
            outputs=[gen_name(9)])
S
SunAhong1993 已提交
80
        pattern.add_layer(
S
SunAhong1993 已提交
81 82 83
            "paddle.multiply",
            inputs={"x": "bn-input-0", "y": gen_name(5)},
            outputs=[gen_name(10)])
S
SunAhong1993 已提交
84
        pattern.add_layer(
S
SunAhong1993 已提交
85 86 87
            "paddle.add",
            inputs={"x": gen_name(10), "y": gen_name(9)},
            outputs=[gen_name(11)])
S
SunAhong1993 已提交
88 89
        pattern.build(inputs={"input-0": "bn-input-0", })
        self.patterns.append(pattern)
S
SunAhong1993 已提交
90
        
S
SunAhong1993 已提交
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
        pattern = PaddleGraph(graph_type="dygraph")
        pattern.add_layer(
            "self.create_parameter",
            inputs={},
            outputs=[gen_name(0)])
        pattern.add_layer(
            "paddle.full",
            inputs={},
            outputs=[gen_name(1)],
            shape=[1])
        pattern.add_layer(
            "paddle.add",
            inputs={"x": gen_name(0), "y": gen_name(1)},
            outputs=[gen_name(2)])
        pattern.add_layer(
            "paddle.rsqrt",
            inputs={"x": gen_name(2)},
            outputs=[gen_name(3)])
        pattern.add_layer(
            "self.create_parameter",
            inputs={},
            outputs=[gen_name(4)])
        pattern.add_layer(
            "paddle.multiply",
            inputs={"x": gen_name(3), "y": gen_name(4)},
            outputs=[gen_name(5)])
        pattern.add_layer(
            "paddle.multiply",
            inputs={"x": "bn-input-0", "y": gen_name(5)},
            outputs=[gen_name(10)])
        pattern.add_layer(
            "self.create_parameter",
            inputs={},
            outputs=[gen_name(6)])
        pattern.add_layer(
            "paddle.multiply",
            inputs={"x": gen_name(6), "y": gen_name(5)},
            outputs=[gen_name(7)])
        pattern.add_layer(
            "self.create_parameter",
            inputs={},
            outputs=[gen_name(8)])
        pattern.add_layer(
S
SunAhong1993 已提交
134
            "paddle.subtract",
S
SunAhong1993 已提交
135 136 137 138 139 140 141 142
            inputs={"x": gen_name(8), "y": gen_name(7)},
            outputs=[gen_name(9)])
        pattern.add_layer(
            "paddle.add",
            inputs={"x": gen_name(10), "y": gen_name(9)},
            outputs=[gen_name(11)])
        pattern.build(inputs={"input-0": "bn-input-0", })
        self.patterns.append(pattern)
S
SunAhong1993 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182

    def insert_new_layer(self, graph, parameters, matches):
        new_layers, last_layer_id = self.gen_new_layer(matches, parameters, graph)
        matches_copy = copy.deepcopy(matches)
        for layer_id, layer in matches_copy.items():
            for i in range(3):
                if layer_id == new_layers[i].id:
                    matches.pop(new_layers[i].id)
        prefix_layers = OrderedDict()
        mid_layers = OrderedDict()
        suffix_layers = OrderedDict()
        is_need_id = False
        for layer_id, layer in graph.layers.items():
            if is_need_id:
                suffix_layers[layer_id] = layer
            else:
                if layer_id == last_layer_id:
                    for i in range(3):
                        mid_layers[new_layers[i].id] = new_layers[i]
                    is_need_id = True
                prefix_layers[layer_id] = layer
        prefix_layers.update(mid_layers)
        prefix_layers.update(suffix_layers)
        graph.layers = prefix_layers

    def gen_new_layer(self, matches, parameters, graph):
        layer_id_list = list(matches.keys())
        layer_id_list.sort(key = int)
        for layer_id, layer in matches.items():
            if layer.kernel == "paddle.full":
                full_layer = layer
                out_layer_id = graph.edges_out[layer_id][0]
                if matches[out_layer_id].kernel == "paddle.add":
                    var_layer_id = graph.edges_in[out_layer_id][0]
                    var_layer = matches[var_layer_id]
            if layer.kernel == "paddle.rsqrt":
                out_layer_id = graph.edges_out[layer_id][0]
                if matches[out_layer_id].kernel == "paddle.multiply":
                    gamma_layer_id = graph.edges_in[out_layer_id][1]
                    gamma_layer = matches[gamma_layer_id]
S
SunAhong1993 已提交
183
            if layer.kernel == "paddle.subtract":
S
SunAhong1993 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
                in_layer_id = graph.edges_in[layer_id][0]
                beta_layer = matches[in_layer_id]
                in_layer_id = graph.edges_in[layer_id][1]
                in_layer_id = graph.edges_in[in_layer_id][0]
                mean_layer = matches[in_layer_id]
                out_layer_id = graph.edges_out[layer_id][0]
                add_layer = matches[out_layer_id]
            if layer.kernel == "paddle.multiply":
                in_layer_id = graph.edges_in[layer_id][1]
                mul_layer = matches[in_layer_id]
                if mul_layer.kernel == "paddle.multiply":
                    in_layer_id = graph.edges_in[layer_id][0]
                    if in_layer_id not in matches:
                        input_name = layer.inputs["x"]
        transpose0 = PaddleLayer(
            id=layer_id_list[-1] + "_1",
            kernel="paddle.transpose",
            inputs={"x": input_name},
            outputs=["{}_transpose_for_bn".format(input_name)],
            perm=[0, 3, 1, 2])
        bn_name = "merge_bn{}".format(self.bn_index)
        self.bn_index += 1
        params = parameters[gamma_layer.outputs[0]]
        c = params.shape[0]
        bn = PaddleLayer(
            id=layer_id_list[-1] + "_2",
            kernel="paddle.nn.BatchNorm",
            inputs={"input": "{}_transpose_for_bn".format(input_name)},
            outputs=[bn_name, "{}_bn".format(input_name)],
            num_channels=c,
            epsilon=full_layer.attrs["fill_value"],
            param_attr=string(gamma_layer.outputs[0]),
            bias_attr=string(beta_layer.outputs[0]),
            moving_mean_name=string(mean_layer.outputs[0]),
            moving_variance_name=string(var_layer.outputs[0]),
            is_test=True)
        transpose1 = PaddleLayer(
            id=layer_id_list[-1] + "_3",
            kernel="paddle.transpose",
            inputs={"x": "{}_bn".format(input_name)},
            outputs=add_layer.outputs,
            perm=[0, 2, 3, 1])
        return [transpose0, bn, transpose1], layer_id_list[-1]