| 1 | // Tencent is pleased to support the open source community by making ncnn available. |
| 2 | // |
| 3 | // Copyright (C) 2023 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_maxpool_unpack.h" |
| 16 | #include <algorithm> |
| 17 | #include "pass_level2.h" |
| 18 | |
| 19 | namespace pnnx { |
| 20 | |
| 21 | void fuse_maxpool_unpack(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 != "nn.MaxPool1d" && op->type != "nn.MaxPool2d" && op->type != "nn.MaxPool3d") |
| 32 | continue; |
| 33 | |
| 34 | Operator* op2 = op->outputs[0]->consumers[0]; |
| 35 | |
| 36 | if (op->outputs.size() == 1 && op2->type != "prim::TupleUnpack") |
| 37 | { |
| 38 | if (op->params.find("return_indices") == op->params.end()) |
| 39 | continue; |
| 40 | |
| 41 | if (op->params.at("return_indices").b == false) |
| 42 | continue; |
| 43 | |
| 44 | matched = true; |
| 45 | |
| 46 | // no indices returned actually |
| 47 | op->params["return_indices"] = false; |
| 48 | break; |
| 49 | } |
| 50 | |
| 51 | if (op->outputs.size() != 1) |
| 52 | continue; |
| 53 | |
| 54 | if (op->outputs[0]->consumers.size() != 1) |
| 55 | continue; |
| 56 | |
| 57 | if (op2->type != "prim::TupleUnpack") |
| 58 | continue; |
| 59 | |
| 60 | matched = true; |
| 61 | |
| 62 | op->outputs[0]->producer = 0; |
| 63 | op->outputs[0]->remove_consumer(op2); |
| 64 | |
| 65 | for (auto& x : op2->outputs) |
| 66 | { |
| 67 | x->producer = op; |
| 68 | } |
| 69 | |
| 70 | op->outputs = op2->outputs; |
| 71 | |
| 72 | op2->inputs.clear(); |
| 73 | op2->outputs.clear(); |
| 74 | |
| 75 | graph.ops.erase(std::find(graph.ops.begin(), graph.ops.end(), op2)); |
| 76 | |
| 77 | delete op2; |
| 78 | |
| 79 | break; |
| 80 | } |
| 81 | |
| 82 | if (!matched) |
| 83 | break; |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | } // namespace pnnx |