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 11 kB

5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. /**
  2. * Copyright 2019-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 "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. static inline AnfNodePtr DoTransform(const OptimizerPtr &optimizer, const AnfNodePtr &node,
  94. const SubstitutionPtr &substitution) {
  95. auto manager = optimizer->manager();
  96. bool is_match = substitution->predicate_(node);
  97. if (is_match) {
  98. TraceGuard trace_guard(std::make_shared<TraceOpt>(node->debug_info()));
  99. auto res = (*substitution)(optimizer, node);
  100. if (res != nullptr && res != node) {
  101. #ifdef ENABLE_PROFILE
  102. double t = GetTime();
  103. #endif
  104. MS_LOG(DEBUG) << "Replace " << node->DebugString() << " with " << res->DebugString() << ", by "
  105. << substitution->name_;
  106. (void)manager->Replace(node, res);
  107. #ifdef ENABLE_PROFILE
  108. MsProfile::StatTime("replace." + substitution->name_, GetTime() - t);
  109. #endif
  110. return res;
  111. }
  112. }
  113. return nullptr;
  114. }
  115. static inline void UpdateTransformingList(const OptimizerPtr &optimizer, const AnfNodePtr &node,
  116. std::deque<AnfNodePtr> *todo, bool change, size_t seen) {
  117. if (IsValueNode<FuncGraph>(node)) {
  118. (*todo).emplace_back(GetValueNode<FuncGraphPtr>(node)->output());
  119. }
  120. if (node->isa<CNode>()) {
  121. auto &inputs = node->cast<CNodePtr>()->inputs();
  122. (void)std::copy(inputs.begin(), inputs.end(), std::back_inserter(*todo));
  123. }
  124. if (!change) {
  125. return;
  126. }
  127. auto manager = optimizer->manager();
  128. auto &node_users = manager->node_users();
  129. auto users_iterator = node_users.find(node);
  130. if (users_iterator == node_users.end()) {
  131. return;
  132. }
  133. auto users = users_iterator->second;
  134. for (auto &use : users) {
  135. auto use_node = use.first;
  136. if (use_node == nullptr) {
  137. continue;
  138. }
  139. (*todo).emplace_back(use_node);
  140. if (use_node->seen_ == seen) {
  141. use_node->seen_--;
  142. }
  143. }
  144. }
  145. bool SubstitutionList::ApplyIRToSubstitutions(const OptimizerPtr &optimizer, const FuncGraphPtr &func_graph) const {
  146. #ifdef ENABLE_PROFILE
  147. double start = GetTime();
  148. #endif
  149. FuncGraphManagerPtr manager = optimizer->manager();
  150. auto seen = NewSeenGeneration();
  151. // 1024 is for the initial capacity of deque
  152. std::deque<AnfNodePtr> todo(1024);
  153. todo.clear();
  154. todo.emplace_back(func_graph->output());
  155. bool changes = false;
  156. auto &all_nodes = manager->all_nodes();
  157. while (!todo.empty()) {
  158. AnfNodePtr node = todo.front();
  159. todo.pop_front();
  160. if (node == nullptr || node->seen_ == seen || !isTraversable(node) || !all_nodes.contains(node)) {
  161. continue;
  162. }
  163. node->seen_ = seen;
  164. bool change = false;
  165. for (auto &substitution : list_) {
  166. auto res = DoTransform(optimizer, node, substitution);
  167. if (res != nullptr) {
  168. change = true;
  169. changes = true;
  170. node = res;
  171. todo.emplace_back(res);
  172. break;
  173. }
  174. }
  175. UpdateTransformingList(optimizer, node, &todo, change, seen);
  176. }
  177. #ifdef ENABLE_PROFILE
  178. MsProfile::StatTime("opt.transforms." + optimizer->name(), GetTime() - start);
  179. #endif
  180. return changes;
  181. }
  182. bool SubstitutionList::ApplySubstitutionToIR(const OptimizerPtr &optimizer, const AnfNodePtr &root_node,
  183. const SubstitutionPtr &substitution) const {
  184. #ifdef ENABLE_PROFILE
  185. double start = GetTime();
  186. #endif
  187. FuncGraphManagerPtr manager = optimizer->manager();
  188. auto seen = NewSeenGeneration();
  189. // 1024 is for the initial capacity of deque
  190. std::deque<AnfNodePtr> todo(1024);
  191. todo.clear();
  192. todo.emplace_back(root_node);
  193. bool changes = false;
  194. auto &all_nodes = manager->all_nodes();
  195. while (!todo.empty()) {
  196. AnfNodePtr node = todo.front();
  197. todo.pop_front();
  198. if (node == nullptr || node->seen_ == seen || !isTraversable(node) || !all_nodes.contains(node)) {
  199. continue;
  200. }
  201. node->seen_ = seen;
  202. bool change = false;
  203. auto res = DoTransform(optimizer, node, substitution);
  204. if (res != nullptr) {
  205. change = true;
  206. changes = true;
  207. node = res;
  208. }
  209. UpdateTransformingList(optimizer, node, &todo, change, seen);
  210. }
  211. #ifdef ENABLE_PROFILE
  212. MsProfile::StatTime("opt.transform." + optimizer->name(), GetTime() - start);
  213. #endif
  214. return changes;
  215. }
  216. bool SubstitutionList::ApplySubstitutionsToIR(const OptimizerPtr &optimizer, const FuncGraphPtr &func_graph) const {
  217. // Add for substitution status counting
  218. size_t space = 0;
  219. std::unordered_map<std::string, std::vector<bool>> status;
  220. if (optimizer->is_on_debug_) {
  221. for (size_t i = 0; i < list_.size(); i++) {
  222. status[list_[i]->name_ + std::to_string(i)] = {};
  223. }
  224. }
  225. bool changes = false;
  226. bool loop = true;
  227. while (loop) {
  228. loop = false;
  229. for (size_t i = 0; i < list_.size(); i++) {
  230. const auto &substitution = list_[i];
  231. bool change = ApplySubstitutionToIR(optimizer, func_graph->output(), substitution);
  232. changes = changes || change;
  233. loop = loop || change;
  234. static const auto enable_dump_pass_ir = (common::GetEnv("ENV_DUMP_PASS_IR") == "1");
  235. if (enable_dump_pass_ir && MsContext::GetInstance()->get_param<bool>(MS_CTX_SAVE_GRAPHS_FLAG)) {
  236. auto fg_name = optimizer->name() + "_r" + std::to_string(optimizer->CurPass_.counter) + "_" +
  237. optimizer->CurPass_.name + "_" + substitution->name_;
  238. DumpIR(fg_name + ".ir", func_graph);
  239. if (MsContext::GetInstance()->get_param<int>(MS_CTX_EXECUTION_MODE) != kPynativeMode) {
  240. func_graph->DumpFuncGraph(fg_name);
  241. ExportIR(fg_name + ".dat", "", func_graph);
  242. }
  243. }
  244. // Record the status of each substitution
  245. if (optimizer->is_on_debug_) {
  246. status[substitution->name_ + std::to_string(i)].push_back(change);
  247. space = std::max(substitution->name_.size(), space);
  248. }
  249. }
  250. if (is_once_) {
  251. break;
  252. }
  253. }
  254. // Display the status of each substitution
  255. if (optimizer->is_on_debug_) {
  256. std::stringstream ss;
  257. ss << std::endl
  258. << "Pass: " << optimizer->name() << "(" << optimizer->CurPass_.counter << ")_" << optimizer->CurPass_.name
  259. << std::endl;
  260. for (size_t i = 0; i < list_.size(); i++) {
  261. auto name = list_[i]->name_;
  262. ss << std::left << std::setw(space + 4) << name << "\t";
  263. for (auto change : status[name + std::to_string(i)]) {
  264. ss << change << " ";
  265. }
  266. ss << std::endl;
  267. }
  268. MS_LOG(DEBUG) << ss.str();
  269. }
  270. return changes;
  271. }
  272. bool SubstitutionList::operator()(const FuncGraphPtr &func_graph, const OptimizerPtr &optimizer) const {
  273. MS_EXCEPTION_IF_NULL(optimizer);
  274. MS_EXCEPTION_IF_NULL(func_graph);
  275. FuncGraphManagerPtr manager = optimizer->manager();
  276. manager->AddFuncGraph(func_graph);
  277. bool changes = false;
  278. static const auto traverse_mode =
  279. (common::GetEnv("ENV_TRAVERSE_SUBSTITUTIONS_MODE") != "1" ? kOptTraverseFromIRToSubstitutions
  280. : kOptTraverseFromSubstitutionsToIR);
  281. if (traverse_mode == kOptTraverseFromIRToSubstitutions &&
  282. MsContext::GetInstance()->get_param<int>(MS_CTX_EXECUTION_MODE) != kPynativeMode &&
  283. optimizer->traverse_nodes_first() && !is_once_ && !global_sensitive_) {
  284. MS_LOG(DEBUG) << "IR >> SUB, " << optimizer->name() << "(r" << optimizer->CurPass_.counter << ")_"
  285. << optimizer->CurPass_.name;
  286. changes = ApplyIRToSubstitutions(optimizer, func_graph);
  287. } else {
  288. MS_LOG(DEBUG) << "SUB >> IR, " << optimizer->name() << "(r" << optimizer->CurPass_.counter << ")_"
  289. << optimizer->CurPass_.name;
  290. changes = ApplySubstitutionsToIR(optimizer, func_graph);
  291. }
  292. return changes;
  293. }
  294. } // namespace opt
  295. } // namespace mindspore