Elffuss BraidHub

kikocis/ncnn public

master · 5.0 KiBRawPermalink
1// Tencent is pleased to support the open source community by making ncnn available.
2//
3// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
4//
5// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
6// in compliance with the License. You may obtain a copy of the License at
7//
8// https://opensource.org/licenses/BSD-3-Clause
9//
10// Unless required by applicable law or agreed to in writing, software distributed
11// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
12// CONDITIONS OF ANY KIND, either express or implied. See the License for the
13// specific language governing permissions and limitations under the License.
14
15#include "fuse_conv2d_batchnorm2d.h"
16
17#include "pass_level2.h"
18
19#include <math.h>
20#include <string.h>
21
22namespace pnnx {
23
24class fuse_conv2d_batchnorm2d_pass : public GraphRewriterPass
25{
26public:
27 const char* match_pattern_graph() const
28 {
29 return R"PNNXIR(7767517
304 3
31pnnx.Input input 0 1 input
32nn.Conv2d op_0 1 1 input a in_channels=%in_channels out_channels=%out_channels kernel_size=%kernel_size stride=%stride padding_mode=%padding_mode padding=%padding dilation=%dilation groups=%groups bias=%bias @weight @bias
33nn.BatchNorm2d op_1 1 1 a out num_features=%num_features eps=%eps affine=%affine @running_mean @running_var @weight @bias
34pnnx.Output output 1 0 out
35)PNNXIR";
36 }
37
38 const char* type_str() const
39 {
40 return "nn.Conv2d";
41 }
42
43 const char* name_str() const
44 {
45 return "convbn2d";
46 }
47
48 void write(Operator* op, const std::map<std::string, Parameter>& captured_params, const std::map<std::string, Attribute>& captured_attrs) const
49 {
50 op->params["in_channels"] = captured_params.at("in_channels");
51 op->params["out_channels"] = captured_params.at("out_channels");
52 op->params["kernel_size"] = captured_params.at("kernel_size");
53 op->params["padding_mode"] = captured_params.at("padding_mode");
54 op->params["stride"] = captured_params.at("stride");
55 op->params["padding"] = captured_params.at("padding");
56 op->params["dilation"] = captured_params.at("dilation");
57 op->params["groups"] = captured_params.at("groups");
58 op->params["bias"] = true;
59
60 // resolve merged conv2d weight and bias
61 int channels = captured_params.at("num_features").i;
62 float bn_eps = captured_params.at("eps").f;
63 bool has_bn_affine = captured_params.at("affine").b;
64 bool has_conv_bias = captured_params.at("bias").b;
65
66 auto bn_running_mean = captured_attrs.at("op_1.running_mean").get_float32_data();
67 auto bn_running_var = captured_attrs.at("op_1.running_var").get_float32_data();
68 auto bn_weight = has_bn_affine ? captured_attrs.at("op_1.weight").get_float32_data() : std::vector<float>();
69 auto bn_bias = has_bn_affine ? captured_attrs.at("op_1.bias").get_float32_data() : std::vector<float>();
70
71 // a = bias - slope * mean / sqrt(var + eps)
72 // b = slope / sqrt(var + eps)
73 // value = value * b + a
74
75 std::vector<float> a(channels);
76 std::vector<float> b(channels);
77 for (int i = 0; i < channels; i++)
78 {
79 double sqrt_var = sqrt(bn_running_var[i] + bn_eps);
80
81 if (has_bn_affine)
82 {
83 a[i] = (float)(bn_bias[i] - bn_weight[i] * bn_running_mean[i] / sqrt_var);
84 b[i] = (float)(bn_weight[i] / sqrt_var);
85 }
86 else
87 {
88 a[i] = (float)(-bn_running_mean[i] / sqrt_var);
89 b[i] = (float)(1.f / sqrt_var);
90 }
91 }
92
93 op->attrs["weight"] = captured_attrs.at("op_0.weight");
94
95 if (has_conv_bias)
96 {
97 op->attrs["bias"] = captured_attrs.at("op_0.bias");
98 }
99 else
100 {
101 // init bias as zero
102 op->attrs["bias"] = Attribute();
103 op->attrs["bias"].type = op->attrs["weight"].type;
104 op->attrs["bias"].shape = {channels};
105 op->attrs["bias"].set_float32_data(std::vector<float>(channels, 0.f));
106 }
107
108 auto conv_weight = op->attrs["weight"].get_float32_data();
109 auto conv_bias = op->attrs["bias"].get_float32_data();
110
111 const int outch = captured_params.at("out_channels").i;
112 const int weight_per_outch = op->attrs["weight"].elemcount() / outch;
113
114 for (int i = 0; i < channels; i++)
115 {
116 float* conv_weight_outch = conv_weight.data() + weight_per_outch * i;
117 for (int j = 0; j < weight_per_outch; j++)
118 {
119 conv_weight_outch[j] *= b[i];
120 }
121
122 conv_bias[i] = conv_bias[i] * b[i] + a[i];
123 }
124
125 op->attrs["weight"].set_float32_data(conv_weight);
126 op->attrs["bias"].set_float32_data(conv_bias);
127 }
128};
129
130void fuse_conv2d_batchnorm2d(Graph& graph)
131{
132 fuse_conv2d_batchnorm2d_pass a;
133 int opindex = 0;
134
135 pnnx_graph_rewrite(graph, &a, opindex);
136}
137
138} // namespace pnnx