| 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 "fold_constants.h" |
| 16 | #include <unordered_set> |
| 17 | |
| 18 | #include "storezip.h" |
| 19 | #include "pass_level4/dead_code_elimination.h" |
| 20 | |
| 21 | namespace pnnx { |
| 22 | |
| 23 | void fold_constants(Graph& graph, const std::set<std::string>& foldable_constants, const std::string& foldable_constants_zippath) |
| 24 | { |
| 25 | if (foldable_constants.empty()) |
| 26 | return; |
| 27 | |
| 28 | StoreZipReader zip; |
| 29 | zip.open(foldable_constants_zippath); |
| 30 | |
| 31 | for (size_t i = 0; i < graph.operands.size(); i++) |
| 32 | { |
| 33 | Operand* operand = graph.operands[i]; |
| 34 | const std::string& name = operand->name; |
| 35 | |
| 36 | if (foldable_constants.find(name) == foldable_constants.end()) |
| 37 | continue; |
| 38 | |
| 39 | Operator* op = operand->producer; |
| 40 | if (op->type == "pnnx.Attribute") |
| 41 | continue; |
| 42 | |
| 43 | // replace producer with attribute |
| 44 | Operator* op_new = graph.new_operator_before("pnnx.Attribute", std::string("pnnx_fold_") + name, op); |
| 45 | |
| 46 | op_new->attrs["data"] = Attribute(); |
| 47 | |
| 48 | Attribute& t2 = op_new->attrs["data"]; |
| 49 | t2.type = operand->type; |
| 50 | t2.shape = operand->shape; |
| 51 | size_t size = zip.get_file_size(name); |
| 52 | t2.data.resize(size); |
| 53 | zip.read_file(name, t2.data.data()); |
| 54 | |
| 55 | op_new->outputs.push_back(operand); |
| 56 | operand->producer = op_new; |
| 57 | |
| 58 | op->outputs.clear(); |
| 59 | } |
| 60 | |
| 61 | zip.close(); |
| 62 | |
| 63 | // dce |
| 64 | dead_code_elimination(graph); |
| 65 | } |
| 66 | |
| 67 | } // namespace pnnx |