Elffuss BraidHub

kikocis/ncnn public

master · 2.5 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 "fuse_rnn_unpack.h"
16#include <algorithm>
17#include "pass_level2.h"
18
19namespace pnnx {
20
21void fuse_rnn_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.RNN" && op->type != "nn.LSTM" && op->type != "nn.GRU")
32 continue;
33
34 if (op->outputs.size() != 1)
35 continue;
36
37 if (op->outputs[0]->consumers.size() != 1)
38 continue;
39
40 Operator* op2 = op->outputs[0]->consumers[0];
41 if (op2->type != "prim::TupleUnpack")
42 continue;
43
44 matched = true;
45
46 op->outputs[0]->producer = 0;
47 op->outputs[0]->remove_consumer(op2);
48
49 for (auto& x : op2->outputs)
50 {
51 x->producer = op;
52 }
53
54 op->outputs = op2->outputs;
55
56 // outputs may be swapped, fix the ugly order
57 if (op->params.find("pnnx_rnn_output_swapped") != op->params.end() && op->params.at("pnnx_rnn_output_swapped").i == 1)
58 {
59 op->params.erase("pnnx_rnn_output_swapped");
60 if (op->type == "nn.RNN" || op->type == "nn.GRU")
61 {
62 std::swap(op->outputs[0], op->outputs[1]);
63 }
64 if (op->type == "nn.LSTM")
65 {
66 std::swap(op->outputs[0], op->outputs[2]);
67 std::swap(op->outputs[1], op->outputs[2]);
68 }
69 }
70
71 op2->inputs.clear();
72 op2->outputs.clear();
73
74 graph.ops.erase(std::find(graph.ops.begin(), graph.ops.end(), op2));
75
76 delete op2;
77
78 break;
79 }
80
81 if (!matched)
82 break;
83 }
84}
85
86} // namespace pnnx