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.

opt.cc 7.2 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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 "frontend/optimizer/opt.h"
  17. #include <deque>
  18. #include <memory>
  19. #include <unordered_map>
  20. #include <algorithm>
  21. #include "ir/anf.h"
  22. #include "ir/manager.h"
  23. #include "frontend/optimizer/optimizer.h"
  24. #include "utils/log_adapter.h"
  25. namespace mindspore {
  26. /* namespace to support opt */
  27. namespace opt {
  28. SubstitutionPtr MakeSubstitution(const OptimizerCallerPtr &transform, const std::string &name, const PrimitivePtr &prim,
  29. const RenormAction &renorm_action) {
  30. auto fn = [prim](const AnfNodePtr &node) -> bool { return IsPrimitiveCNode(node, prim); };
  31. return std::make_shared<Substitution>(transform, name, fn, renorm_action);
  32. }
  33. SubstitutionPtr MakeSubstitution(const OptimizerCallerPtr &transform, const std::string &name,
  34. const std::vector<PrimitivePtr> &prims, const RenormAction &renorm_action) {
  35. auto fn = [prims](const AnfNodePtr &node) -> bool {
  36. if (!node->isa<CNode>()) {
  37. return false;
  38. }
  39. auto cnode = node->cast<CNodePtr>();
  40. auto inp0 = cnode->input(0);
  41. auto prim0 = GetValueNode<PrimitivePtr>(inp0);
  42. if (prim0 == nullptr) {
  43. return false;
  44. }
  45. auto hash = prim0->Hash();
  46. auto const &name = prim0->name();
  47. for (auto &prim : prims) {
  48. if (hash == prim->Hash() && name == prim->name()) {
  49. return true;
  50. }
  51. }
  52. return false;
  53. };
  54. return std::make_shared<Substitution>(transform, name, fn, renorm_action);
  55. }
  56. SubstitutionPtr MakeSubstitution(const OptimizerCallerPtr &transform, const std::string &name,
  57. const PredicateFuncType &predicate, const RenormAction &renorm_action) {
  58. return std::make_shared<Substitution>(transform, name, predicate, renorm_action);
  59. }
  60. AnfNodePtr Substitution::operator()(const OptimizerPtr &optimizer, const AnfNodePtr &node) {
  61. #ifdef ENABLE_PROFILE
  62. double t = GetTime();
  63. #endif
  64. AnfNodePtr result = (*transform_)(optimizer, node);
  65. #ifdef ENABLE_PROFILE
  66. if (optimizer != nullptr) {
  67. auto time = GetTime();
  68. MsProfile::StatTime("substitution." + name_, time - t);
  69. if (result != nullptr) {
  70. MsProfile::StatTime("match." + name_, time - t);
  71. }
  72. }
  73. #endif
  74. if (optimizer != nullptr && optimizer->is_watch_renormalize() && result != nullptr) {
  75. if ((renorm_action_ == FORCE_RENORM) || (result->abstract() == nullptr)) {
  76. optimizer->set_is_untyped_generated();
  77. }
  78. }
  79. return result;
  80. }
  81. static bool isTraversable(const AnfNodePtr &node) {
  82. if (node == nullptr) {
  83. return false;
  84. }
  85. if (node->isa<CNode>() || node->isa<Parameter>()) {
  86. return true;
  87. }
  88. if (IsValueNode<FuncGraph>(node) || IsValueNode<RefKey>(node)) {
  89. return true;
  90. }
  91. return false;
  92. }
  93. bool SubstitutionList::ApplyTransform(const OptimizerPtr &optimizer, const AnfNodePtr &root_node,
  94. const SubstitutionPtr &transform) const {
  95. #ifdef ENABLE_PROFILE
  96. double start = GetTime();
  97. #endif
  98. FuncGraphManagerPtr manager = optimizer->manager();
  99. auto seen = NewSeenGeneration();
  100. // 1024 is for the initial capacity of deque
  101. std::deque<AnfNodePtr> todo(1024);
  102. todo.clear();
  103. todo.push_back(root_node);
  104. bool changes = false;
  105. auto &all_nodes = manager->all_nodes();
  106. while (!todo.empty()) {
  107. AnfNodePtr node = todo.front();
  108. todo.pop_front();
  109. // check whether this node has been matched.
  110. if (node == nullptr || node->seen_ == seen || !isTraversable(node) || !all_nodes.contains(node)) {
  111. continue;
  112. }
  113. node->seen_ = seen;
  114. // select nodes that this transform can be applied.
  115. bool is_match = transform->predicate_(node);
  116. // apply transform on this node
  117. bool change = false;
  118. if (is_match) {
  119. auto ret = (*transform)(optimizer, node);
  120. if (ret != nullptr && ret != node) {
  121. change = true;
  122. changes = true;
  123. #ifdef ENABLE_PROFILE
  124. double t = GetTime();
  125. #endif
  126. (void)manager->Replace(node, ret);
  127. #ifdef ENABLE_PROFILE
  128. MsProfile::StatTime("replace." + transform->name_, GetTime() - t);
  129. #endif
  130. node = ret;
  131. }
  132. }
  133. // find success, and add them to todo list
  134. if (IsValueNode<FuncGraph>(node)) {
  135. todo.push_back(GetValueNode<FuncGraphPtr>(node)->output());
  136. }
  137. if (node->isa<CNode>()) {
  138. auto &inputs = node->cast<CNodePtr>()->inputs();
  139. (void)std::copy(inputs.begin(), inputs.end(), std::back_inserter(todo));
  140. }
  141. auto &node_users = manager->node_users();
  142. if (change && node_users.find(node) != node_users.end()) {
  143. for (auto &use : node_users[node]) {
  144. auto use_node = use.first;
  145. if (use_node == nullptr) {
  146. continue;
  147. }
  148. todo.push_back(use_node);
  149. if (use_node->seen_ == seen) {
  150. use_node->seen_--;
  151. }
  152. }
  153. }
  154. }
  155. #ifdef ENABLE_PROFILE
  156. MsProfile::StatTime("opt.transform." + optimizer->name(), GetTime() - start);
  157. #endif
  158. return changes;
  159. }
  160. bool SubstitutionList::operator()(const FuncGraphPtr &func_graph, const OptimizerPtr &optimizer) const {
  161. MS_EXCEPTION_IF_NULL(optimizer);
  162. MS_EXCEPTION_IF_NULL(func_graph);
  163. FuncGraphManagerPtr manager = optimizer->manager();
  164. manager->AddFuncGraph(func_graph);
  165. // for transform status counting
  166. size_t space = 0;
  167. std::unordered_map<std::string, std::vector<bool>> status;
  168. if (optimizer->is_on_debug_) {
  169. for (size_t i = 0; i < list_.size(); i++) {
  170. status[list_[i]->name_ + std::to_string(i)] = {};
  171. }
  172. }
  173. bool loop = false;
  174. bool changes = false;
  175. do {
  176. loop = false;
  177. for (size_t i = 0; i < list_.size(); i++) {
  178. auto change = ApplyTransform(optimizer, func_graph->output(), list_[i]);
  179. changes = changes || change;
  180. loop = loop || change;
  181. // record the status of each transform
  182. if (optimizer->is_on_debug_) {
  183. status[list_[i]->name_ + std::to_string(i)].push_back(change);
  184. space = std::max(list_[i]->name_.size(), space);
  185. }
  186. }
  187. if (is_once_) {
  188. break;
  189. }
  190. } while (loop);
  191. // display the status of each transform
  192. if (optimizer->is_on_debug_) {
  193. std::stringstream ss;
  194. ss << std::endl
  195. << "Pass: " << optimizer->name() << "(" << optimizer->CurPass_.counter << ")_" << optimizer->CurPass_.name
  196. << std::endl;
  197. for (size_t i = 0; i < list_.size(); i++) {
  198. auto name = list_[i]->name_;
  199. ss << std::left << std::setw(space + 4) << name << "\t";
  200. for (auto change : status[name + std::to_string(i)]) {
  201. ss << change << " ";
  202. }
  203. ss << std::endl;
  204. }
  205. MS_LOG(DEBUG) << ss.str();
  206. }
  207. return changes;
  208. }
  209. } // namespace opt
  210. } // namespace mindspore