Elffuss BraidHub

kikocis/ncnn public

master · 2.1 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_cat.h"
16
17#include <algorithm>
18#include "pass_level2.h"
19
20namespace pnnx {
21
22void eliminate_noop_cat(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 != "torch.cat")
33 continue;
34
35 if (op->inputs.size() > 1)
36 continue;
37
38 // delete noop-like cat
39 matched = true;
40
41 op->inputs[0]->remove_consumer(op);
42
43 Operand* cat_out = op->outputs[0];
44
45 for (auto& x : cat_out->consumers)
46 {
47 for (size_t j = 0; j < x->inputs.size(); j++)
48 {
49 if (x->inputs[j] == cat_out)
50 x->inputs[j] = op->inputs[0];
51 }
52
53 op->inputs[0]->consumers.push_back(x);
54 }
55
56 op->inputs[0]->name = cat_out->name;
57
58 cat_out->producer = 0;
59 cat_out->consumers.clear();
60
61 graph.operands.erase(std::find(graph.operands.begin(), graph.operands.end(), cat_out));
62 delete cat_out;
63
64 op->inputs.clear();
65 op->outputs.clear();
66
67 graph.ops.erase(graph.ops.begin() + i);
68 delete op;
69
70 break;
71 }
72
73 if (!matched)
74 break;
75 }
76}
77
78} // namespace pnnx