Elffuss BraidHub

kikocis/ncnn public

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