Elffuss BraidHub

kikocis/ncnn public

master · 2.8 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 "eliminate_tuple_pair.h"
16
17#include <algorithm>
18#include "pass_level2.h"
19
20namespace pnnx {
21
22void eliminate_tuple_pair(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 != "prim::TupleConstruct")
33 continue;
34
35 if (op->outputs[0]->consumers.size() != 1)
36 continue;
37
38 Operator* op2 = op->outputs[0]->consumers[0];
39 if (op2->type != "prim::TupleUnpack")
40 continue;
41
42 if (op->inputs.size() != op2->outputs.size())
43 continue;
44
45 matched = true;
46
47 const size_t count = op->inputs.size();
48
49 for (size_t j = 0; j < count; j++)
50 {
51 op->inputs[j]->remove_consumer(op);
52
53 for (auto& x : op2->outputs[j]->consumers)
54 {
55 op->inputs[j]->consumers.push_back(x);
56
57 for (size_t k = 0; k < x->inputs.size(); k++)
58 {
59 if (x->inputs[k] == op2->outputs[j])
60 x->inputs[k] = op->inputs[j];
61 }
62 }
63
64 op2->outputs[j]->producer = 0;
65 op2->outputs[j]->consumers.clear();
66
67 graph.operands.erase(std::find(graph.operands.begin(), graph.operands.end(), op2->outputs[j]));
68 delete op2->outputs[j];
69 }
70
71 graph.operands.erase(std::find(graph.operands.begin(), graph.operands.end(), op->outputs[0]));
72 delete op->outputs[0];
73
74 op->inputs.clear();
75 op->outputs.clear();
76
77 op2->inputs.clear();
78 op2->outputs.clear();
79
80 graph.ops.erase(std::find(graph.ops.begin(), graph.ops.end(), op));
81
82 delete op;
83
84 graph.ops.erase(std::find(graph.ops.begin(), graph.ops.end(), op2));
85
86 delete op2;
87
88 break;
89 }
90
91 if (!matched)
92 break;
93 }
94}
95
96} // namespace pnnx