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