| 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 "convert_torch_split.h" |
| 16 | |
| 17 | namespace pnnx { |
| 18 | |
| 19 | namespace ncnn { |
| 20 | |
| 21 | void convert_torch_split(Graph& graph) |
| 22 | { |
| 23 | int op_index = 0; |
| 24 | |
| 25 | for (Operator* op : graph.ops) |
| 26 | { |
| 27 | if (op->type != "torch.split") |
| 28 | continue; |
| 29 | |
| 30 | op->type = "Slice"; |
| 31 | op->name = std::string("split_") + std::to_string(op_index++); |
| 32 | |
| 33 | const Parameter& split_size_or_sections = op->params.at("split_size_or_sections"); |
| 34 | if (split_size_or_sections.type != 2 && split_size_or_sections.type != 5) |
| 35 | { |
| 36 | fprintf(stderr, "malformed split split_size_or_sections type %d\n", split_size_or_sections.type); |
| 37 | continue; |
| 38 | } |
| 39 | |
| 40 | const int batch_index = op->inputs[0]->params["__batch_index"].i; |
| 41 | |
| 42 | int axis = op->params.at("dim").i; |
| 43 | if (axis == batch_index) |
| 44 | { |
| 45 | fprintf(stderr, "split along batch axis %d is not supported\n", batch_index); |
| 46 | continue; |
| 47 | } |
| 48 | |
| 49 | if (axis < 0) |
| 50 | { |
| 51 | int input_rank = op->inputs[0]->shape.size(); |
| 52 | axis = input_rank + axis; |
| 53 | } |
| 54 | |
| 55 | if (axis > batch_index) |
| 56 | axis -= 1; |
| 57 | |
| 58 | if (split_size_or_sections.type == 2) |
| 59 | { |
| 60 | const size_t output_size = op->outputs.size(); |
| 61 | op->params["0"].type = 5; |
| 62 | op->params["0"].ai.resize(output_size, split_size_or_sections.i); |
| 63 | op->params["0"].ai[output_size - 1] = -233; |
| 64 | } |
| 65 | else |
| 66 | { |
| 67 | op->params["0"] = split_size_or_sections; |
| 68 | } |
| 69 | |
| 70 | op->params["1"] = axis; |
| 71 | |
| 72 | op->params.erase("split_size_or_sections"); |
| 73 | op->params.erase("dim"); |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | } // namespace ncnn |
| 78 | |
| 79 | } // namespace pnnx |