Elffuss BraidHub

kikocis/ncnn public

master · 2.8 KiBRawPermalink
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 "convert_torch_unbind.h"
16
17namespace pnnx {
18
19namespace ncnn {
20
21void convert_torch_unbind(Graph& graph)
22{
23 int op_index = 0;
24
25 while (1)
26 {
27 bool matched = false;
28
29 for (Operator* op : graph.ops)
30 {
31 if (op->type != "torch.unbind")
32 continue;
33
34 matched = true;
35
36 op->type = "Slice";
37 op->name = std::string("unbind_") + std::to_string(op_index++);
38
39 const int batch_index = op->inputs[0]->params["__batch_index"].i;
40
41 int axis = op->params.at("dim").i;
42 if (axis == batch_index)
43 {
44 fprintf(stderr, "unbind along batch axis %d is not supported\n", batch_index);
45 continue;
46 }
47
48 if (axis < 0)
49 {
50 int input_rank = op->inputs[0]->shape.size();
51 axis = input_rank + axis;
52 }
53
54 int output_size = (int)op->outputs.size();
55
56 if (axis > batch_index)
57 axis -= 1;
58
59 op->params["0"].type = 5;
60 op->params["0"].ai.resize(output_size, -233);
61
62 op->params["1"] = axis;
63
64 op->params.erase("dim");
65
66 // reshape for each output, squeezing the unbind dim
67 for (int i = 0; i < output_size; i++)
68 {
69 Operand* out = op->outputs[i];
70
71 Operator* reshape = graph.new_operator_after("Tensor.reshape", op->name + "_ncnnreshape" + std::to_string(i), op);
72
73 Operand* reshape_in = graph.new_operand(op->name + "_ncnnreshape" + std::to_string(i) + "_in");
74
75 reshape->inputs.push_back(reshape_in);
76 reshape->outputs.push_back(out);
77
78 op->outputs[i] = reshape_in;
79
80 out->producer = reshape;
81 reshape_in->producer = op;
82 reshape_in->consumers.push_back(reshape);
83
84 reshape->params["shape"] = out->shape;
85 }
86
87 break;
88 }
89
90 if (!matched)
91 break;
92 }
93}
94
95} // namespace ncnn
96
97} // namespace pnnx