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