Elffuss BraidHub

kikocis/ncnn public

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