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