Elffuss BraidHub

kikocis/ncnn public

master · 2.5 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 "expand_quantization_modules.h"
16#include <algorithm>
17#include "pass_level2.h"
18
19namespace pnnx {
20
21void expand_quantization_modules(Graph& graph)
22{
23 while (1)
24 {
25 bool matched = false;
26
27 for (size_t i = 0; i < graph.ops.size(); i++)
28 {
29 Operator* op = graph.ops[i];
30
31 if (op->type == "nn.intrinsic.quantized.ConvReLU2d")
32 {
33 op->type = "nn.quantized.Conv2d";
34 }
35 else if (op->type == "nn.intrinsic.quantized.LinearReLU")
36 {
37 op->type = "nn.quantized.Linear";
38 }
39 else
40 {
41 continue;
42 }
43
44 // expand to nn.quantized.Conv2d / nn.quantized.Linear + nn.ReLU
45
46 matched = true;
47
48 // insert new operator before all output consumers
49 const Operator* cur = 0;
50 {
51 int cur_index = graph.ops.size() - 1;
52 for (auto& c : op->outputs[0]->consumers)
53 {
54 int c_index = std::find(graph.ops.begin(), graph.ops.end(), c) - graph.ops.begin();
55 cur_index = std::min(cur_index, c_index);
56 }
57
58 cur = graph.ops[cur_index];
59 }
60
61 Operator* op_relu = graph.new_operator_before("nn.ReLU", op->name + "_relu", cur);
62
63 Operand* r0 = graph.new_operand(op->name + "_norelu");
64
65 r0->producer = op;
66 r0->consumers.push_back(op_relu);
67
68 op_relu->inputs.push_back(r0);
69 op_relu->outputs.push_back(op->outputs[0]);
70 op_relu->outputs[0]->producer = op_relu;
71
72 op->outputs[0] = r0;
73
74 break;
75 }
76
77 if (!matched)
78 break;
79 }
80}
81
82} // namespace pnnx