You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

node_pass.cc 2.4 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * Copyright 2019 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 "pre_activate/common/node_pass.h"
  17. #include <unordered_set>
  18. #include <deque>
  19. #include <algorithm>
  20. #include "ir/anf.h"
  21. #include "ir/func_graph.h"
  22. #include "ir/manager.h"
  23. #include "session/anf_runtime_algorithm.h"
  24. namespace mindspore {
  25. namespace opt {
  26. bool NodePass::Run(const FuncGraphPtr &func_graph) {
  27. MS_EXCEPTION_IF_NULL(func_graph);
  28. FuncGraphManagerPtr manager = func_graph->manager();
  29. MS_EXCEPTION_IF_NULL(manager);
  30. manager->AddFuncGraph(func_graph);
  31. std::unordered_set<AnfNodePtr> seen_node;
  32. std::deque<AnfNodePtr> todo{func_graph->output()};
  33. bool changes = false;
  34. while (!todo.empty()) {
  35. AnfNodePtr node = todo.front();
  36. todo.pop_front();
  37. if (seen_node.count(node) > 0 || !manager->all_nodes().contains(node)) {
  38. continue;
  39. }
  40. (void)seen_node.insert(node);
  41. AnfNodePtr new_node = Run(func_graph, node);
  42. bool change = (new_node != nullptr);
  43. if (new_node != nullptr && new_node != node) {
  44. (void)manager->Replace(node, new_node);
  45. (void)seen_node.erase(node);
  46. } else if (new_node == nullptr) {
  47. new_node = node;
  48. }
  49. if (new_node && IsValueNode<FuncGraph>(new_node)) {
  50. auto const_func_graph = GetValueNode<FuncGraphPtr>(new_node);
  51. MS_EXCEPTION_IF_NULL(const_func_graph);
  52. if (!const_func_graph->has_attr(FUNC_GRAPH_ATTR_GRAPH_KERNEL)) {
  53. todo.push_back(const_func_graph->output());
  54. }
  55. } else if (new_node && new_node->isa<CNode>()) {
  56. if (AnfAlgo::IsGraphKernel(new_node)) {
  57. todo.push_back(new_node);
  58. }
  59. auto cnode = new_node->cast<CNodePtr>();
  60. MS_EXCEPTION_IF_NULL(cnode);
  61. auto inputs = cnode->inputs();
  62. (void)todo.insert(todo.end(), inputs.begin(), inputs.end());
  63. }
  64. changes = changes || change;
  65. }
  66. return changes;
  67. }
  68. } // namespace opt
  69. } // namespace mindspore