| 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 "constant_unpooling.h" |
| 16 | |
| 17 | #include <unordered_map> |
| 18 | #include <unordered_set> |
| 19 | |
| 20 | namespace pnnx { |
| 21 | |
| 22 | void ConstantUnpooling(std::shared_ptr<torch::jit::Graph>& graph, torch::jit::Block* block, std::unordered_set<torch::jit::Node*>& constants) |
| 23 | { |
| 24 | for (auto it = block->nodes().begin(); it != block->nodes().end();) |
| 25 | { |
| 26 | auto node = *it; |
| 27 | // node may be moved to a different block so advance iterator now |
| 28 | ++it; |
| 29 | |
| 30 | if (!node->blocks().empty()) |
| 31 | { |
| 32 | // Traverse sub-blocks. |
| 33 | for (auto block : node->blocks()) |
| 34 | { |
| 35 | ConstantUnpooling(graph, block, constants); |
| 36 | } |
| 37 | |
| 38 | continue; |
| 39 | } |
| 40 | |
| 41 | for (int i = 0; i < (int)node->inputs().size(); i++) |
| 42 | { |
| 43 | const auto& in = node->input(i); |
| 44 | |
| 45 | if (in->node()->kind() != c10::prim::Constant) |
| 46 | continue; |
| 47 | |
| 48 | // input constant node |
| 49 | if (constants.find(in->node()) == constants.end()) |
| 50 | { |
| 51 | constants.insert(in->node()); |
| 52 | continue; |
| 53 | } |
| 54 | |
| 55 | torch::jit::WithInsertPoint guard(node); |
| 56 | |
| 57 | std::unordered_map<torch::jit::Value*, torch::jit::Value*> value_map; |
| 58 | auto value_map_func = [&](torch::jit::Value* v) { |
| 59 | return value_map.at(v); |
| 60 | }; |
| 61 | |
| 62 | // graph->setInsertPoint(node); |
| 63 | |
| 64 | auto* new_constant_node = graph->insertNode(graph->createClone(in->node(), value_map_func, false)); |
| 65 | |
| 66 | // fprintf(stderr, "new_constant_node %s\n", new_constant_node->outputs()[0]->debugName().c_str()); |
| 67 | |
| 68 | // create new constant node |
| 69 | node->replaceInput(i, new_constant_node->outputs()[0]); |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | void constant_unpooling(std::shared_ptr<torch::jit::Graph>& graph) |
| 75 | { |
| 76 | std::unordered_set<torch::jit::Node*> constants; |
| 77 | ConstantUnpooling(graph, graph->block(), constants); |
| 78 | } |
| 79 | |
| 80 | } // namespace pnnx |