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) 2022 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 "eliminate_noop_pad.h"
16
17#include <algorithm>
18#include "pass_level2.h"
19
20namespace pnnx {
21
22void eliminate_noop_pad(Graph& graph)
23{
24 while (1)
25 {
26 bool matched = false;
27
28 for (size_t i = 0; i < graph.ops.size(); i++)
29 {
30 Operator* op = graph.ops[i];
31
32 if (op->type != "F.pad")
33 continue;
34
35 if (op->params.find("pad") == op->params.end())
36 continue;
37
38 const std::vector<int>& pad = op->params.at("pad").ai;
39
40 bool noop_pad = true;
41 for (auto p : pad)
42 {
43 if (p != 0)
44 {
45 noop_pad = false;
46 break;
47 }
48 }
49
50 if (!noop_pad)
51 continue;
52
53 // delete noop-like pad
54 matched = true;
55
56 for (auto& x : op->inputs)
57 {
58 x->remove_consumer(op);
59 }
60
61 Operand* pad_out = op->outputs[0];
62
63 for (auto& x : pad_out->consumers)
64 {
65 for (size_t j = 0; j < x->inputs.size(); j++)
66 {
67 if (x->inputs[j] == pad_out)
68 x->inputs[j] = op->inputs[0];
69 }
70
71 op->inputs[0]->consumers.push_back(x);
72 }
73
74 op->inputs[0]->name = pad_out->name;
75
76 pad_out->producer = 0;
77 pad_out->consumers.clear();
78
79 graph.operands.erase(std::find(graph.operands.begin(), graph.operands.end(), pad_out));
80 delete pad_out;
81
82 op->inputs.clear();
83 op->outputs.clear();
84
85 graph.ops.erase(graph.ops.begin() + i);
86 delete op;
87
88 break;
89 }
90
91 if (!matched)
92 break;
93 }
94}
95
96} // namespace pnnx