1 /** 2 * Copyright 2020-2021 Huawei Technologies Co., Ltd 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 #include "tools/converter/parser/unused_node_remove_pass.h" 17 #include <deque> 18 #include <unordered_set> 19 #include "tools/optimizer/common/gllo_utils.h" 20 21 namespace mindspore::opt { 22 ProcessGraph(const FuncGraphPtr & func_graph)23STATUS UnusedNodeRemovePass::ProcessGraph(const FuncGraphPtr &func_graph) { 24 MS_ASSERT(func_graph != nullptr); 25 auto return_node = func_graph->get_return(); 26 if (return_node == nullptr) { 27 return RET_OK; 28 } 29 std::unordered_set<AnfNodePtr> vis; 30 std::deque<AnfNodePtr> q; 31 q.push_back(return_node); 32 while (!q.empty()) { 33 auto node = q.front(); 34 vis.insert(node); 35 q.pop_front(); 36 if (utils::isa<CNodePtr>(node)) { 37 auto cnode = utils::cast<CNodePtr>(node); 38 MS_ASSERT(cnode != nullptr); 39 for (auto &input : cnode->inputs()) { 40 if (vis.find(input) == vis.end()) { 41 q.push_back(input); 42 } 43 } 44 } 45 if (utils::isa<ValueNode>(node) && GetValueNode<FuncGraphPtr>(node) != nullptr) { 46 auto sub_graph = GetValueNode<FuncGraphPtr>(node); 47 MS_ASSERT(sub_graph != nullptr); 48 auto status = ProcessGraph(sub_graph); 49 if (status != RET_OK) { 50 MS_LOG(ERROR) << "process sub graph failed"; 51 return RET_ERROR; 52 } 53 } 54 } 55 auto nodes = func_graph->nodes(); 56 auto graph_inputs = func_graph->get_inputs(); 57 for (auto &node : nodes) { 58 if (vis.find(node) == vis.end() && 59 std::find(graph_inputs.begin(), graph_inputs.end(), node) == graph_inputs.end()) { 60 func_graph->DropNode(node); 61 } 62 } 63 return RET_OK; 64 } 65 Run(const FuncGraphPtr & func_graph)66bool UnusedNodeRemovePass::Run(const FuncGraphPtr &func_graph) { 67 MS_ASSERT(func_graph != nullptr); 68 auto status = ProcessGraph(func_graph); 69 return status == RET_OK; 70 } 71 } // namespace mindspore::opt 72