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.

optimizer.h 8.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. #ifndef MINDSPORE_CCSRC_OPTIMIZER_OPTIMIZER_H_
  17. #define MINDSPORE_CCSRC_OPTIMIZER_OPTIMIZER_H_
  18. #include <algorithm>
  19. #include <functional>
  20. #include <iterator>
  21. #include <memory>
  22. #include <string>
  23. #include <vector>
  24. #include <map>
  25. #include <utility>
  26. #include <initializer_list>
  27. #include "debug/draw.h"
  28. #include "debug/anf_ir_dump.h"
  29. #include "debug/anf_ir_utils.h"
  30. #include "debug/trace.h"
  31. #include "optimizer/opt.h"
  32. #include "pipeline/resource.h"
  33. #include "pipeline/action.h"
  34. #include "utils/context/ms_context.h"
  35. namespace mindspore {
  36. namespace opt {
  37. using OptimizeGraphFunc = std::function<bool(const FuncGraphPtr &func_graph, const OptimizerPtr &optimizer)>;
  38. class OptPassConfig {
  39. public:
  40. explicit OptPassConfig(const OptimizeGraphFunc &func) : func_(func) {}
  41. explicit OptPassConfig(const std::vector<SubstitutionPtr> &list, bool is_once = false)
  42. : list_(list), is_once_(is_once) {}
  43. OptPassConfig(const std::initializer_list<SubstitutionPtr> &list, bool is_once = false)
  44. : list_(list), is_once_(is_once) {}
  45. ~OptPassConfig() = default;
  46. const std::vector<SubstitutionPtr> &list() const { return list_; }
  47. const OptimizeGraphFunc &func() const { return func_; }
  48. static OptPassConfig Renormalize() { return OptPassConfig(); }
  49. const bool is_renormalize() const { return is_renormalize_; }
  50. const bool is_once() const { return is_once_; }
  51. private:
  52. OptPassConfig() : is_renormalize_(true) {}
  53. OptimizeGraphFunc func_;
  54. std::vector<SubstitutionPtr> list_;
  55. bool is_renormalize_{false};
  56. bool is_once_{false};
  57. };
  58. class OptPass {
  59. public:
  60. explicit OptPass(const OptimizeGraphFunc &func) : pass_func_(func) {}
  61. ~OptPass() = default;
  62. bool operator()(const FuncGraphPtr &func_graph, const OptimizerPtr &optimizer) const {
  63. return pass_func_(func_graph, optimizer);
  64. }
  65. static OptPass Renormalize() { return OptPass(); }
  66. const bool is_renormalize() const { return is_renormalize_; }
  67. private:
  68. OptPass() : is_renormalize_(true) {}
  69. OptimizeGraphFunc pass_func_;
  70. bool is_renormalize_{false};
  71. };
  72. using OptPassGroupMap = std::vector<std::pair<std::string, OptPassConfig>>;
  73. class Optimizer : public std::enable_shared_from_this<Optimizer> {
  74. public:
  75. Optimizer(const std::string &name, const pipeline::ResourceBasePtr &resource_ptr)
  76. : name_(name), resource_(resource_ptr), run_only_once_(false), is_watch_renormalize_(false), is_enable_(true) {}
  77. virtual ~Optimizer() = default;
  78. void Init(const OptPassGroupMap &passes, bool run_only_once) {
  79. run_only_once_ = run_only_once;
  80. is_watch_renormalize_ = false;
  81. for (auto &iter : passes) {
  82. const std::string &name = iter.first;
  83. pass_names_.push_back(name);
  84. const OptPassConfig &config = iter.second;
  85. if (config.is_renormalize()) {
  86. passes_.push_back(OptPass::Renormalize());
  87. continue;
  88. }
  89. if (config.list().size() > 0) {
  90. OptimizeGraphFunc func = SubstitutionList(config.list(), config.is_once());
  91. passes_.push_back(OptPass(func));
  92. continue;
  93. }
  94. passes_.push_back(OptPass(config.func()));
  95. }
  96. if (passes_.size() == 1) {
  97. run_only_once_ = true;
  98. }
  99. }
  100. static std::shared_ptr<Optimizer> MakeOptimizer(const std::string &name, const pipeline::ResourceBasePtr resource_ptr,
  101. const OptPassGroupMap &passes, bool run_only_once = false,
  102. bool watch_renormalize = false) {
  103. OptimizerPtr optimizer = std::make_shared<Optimizer>(name, resource_ptr);
  104. optimizer->Init(passes, run_only_once);
  105. if (watch_renormalize) {
  106. optimizer->enable_watch_renormalize();
  107. }
  108. return optimizer;
  109. }
  110. FuncGraphPtr step(FuncGraphPtr func_graph, bool use_profile = true) {
  111. if (!is_enable_) {
  112. return func_graph;
  113. }
  114. // Optimizer step counter;
  115. int counter = 1;
  116. bool changes = true;
  117. while (changes) {
  118. changes = false;
  119. auto run_runc = [&counter, &func_graph, &changes, use_profile, this]() {
  120. for (size_t i = 0; i < passes_.size(); ++i) {
  121. const OptPass &opt = passes_[i];
  122. auto opt_func = [&func_graph, &changes, &opt, this]() {
  123. if (opt.is_renormalize()) {
  124. auto resource_ptr = std::dynamic_pointer_cast<pipeline::Resource>(resource_);
  125. if (resource_ptr != nullptr) {
  126. // StepParallel may replace the AbstractValue of the parameters of func_graph,
  127. // So generate the args_spec from parameters.
  128. abstract::AbstractBasePtrList maybe_new_args_spec;
  129. if (is_watch_renormalize_) {
  130. if (untyped_nodes_.size() > 0) {
  131. std::transform(func_graph->parameters().begin(), func_graph->parameters().end(),
  132. std::back_inserter(maybe_new_args_spec),
  133. [](AnfNodePtr param) -> AbstractBasePtr { return param->abstract(); });
  134. func_graph = pipeline::Renormalize(resource_ptr, func_graph, maybe_new_args_spec);
  135. clear_untyped_nodes();
  136. } else {
  137. MS_LOG(INFO) << "Optimizer::step: Skipping Renormalize because untyped_nodes_ is empty.";
  138. }
  139. } else {
  140. std::transform(func_graph->parameters().begin(), func_graph->parameters().end(),
  141. std::back_inserter(maybe_new_args_spec),
  142. [](AnfNodePtr param) -> AbstractBasePtr { return param->abstract(); });
  143. func_graph = pipeline::Renormalize(resource_ptr, func_graph, maybe_new_args_spec);
  144. }
  145. }
  146. } else if (opt(func_graph, shared_from_this())) {
  147. changes = true;
  148. }
  149. };
  150. use_profile ? (WITH(MsProfile::GetProfile()->Step(pass_names_[i])) opt_func) : opt_func();
  151. if (IS_OUTPUT_ON(mindspore::DEBUG) && MsContext::GetInstance()->save_graphs_flag()) {
  152. MS_LOG(DEBUG) << "The opt " << name_ << " round " << counter << " OptPass " << pass_names_[i] << " end.";
  153. auto fg_name =
  154. "opt_substep_" + name_ + "_r" + std::to_string(counter) + "_" + std::to_string(i) + "_" + pass_names_[i];
  155. func_graph->DumpFuncGraph(fg_name);
  156. DumpIR(fg_name + ".ir", func_graph);
  157. ExportIR(fg_name + ".dat", "", func_graph);
  158. MS_LOG(DEBUG) << "Dump " << pass_names_[i] << " func graph.";
  159. }
  160. }
  161. };
  162. use_profile ? (WITH(MsProfile::GetProfile()->Lap(counter++)) run_runc) : run_runc();
  163. if (run_only_once_) {
  164. break;
  165. }
  166. }
  167. return func_graph;
  168. }
  169. pipeline::ResourceBasePtr resource() const { return resource_; }
  170. FuncGraphManagerPtr manager() const {
  171. if (resource_ != nullptr) {
  172. return resource_->manager();
  173. }
  174. MS_LOG(EXCEPTION) << "No ResourceBase exists.";
  175. }
  176. const std::string name() const { return name_; }
  177. void add_node_to_renormalize(AnfNodePtr anode) {
  178. if (std::find(untyped_nodes_.begin(), untyped_nodes_.end(), anode) == untyped_nodes_.end()) {
  179. untyped_nodes_.push_back(anode);
  180. }
  181. }
  182. void clear_untyped_nodes() { untyped_nodes_.clear(); }
  183. void enable_watch_renormalize() { is_watch_renormalize_ = true; }
  184. void disable_watch_renormalize() { is_watch_renormalize_ = false; }
  185. bool is_watch_renormalize() { return is_watch_renormalize_; }
  186. void set_enable(bool enable) { is_enable_ = enable; }
  187. private:
  188. const std::string name_;
  189. pipeline::ResourceBasePtr resource_;
  190. std::vector<OptPass> passes_;
  191. std::vector<std::string> pass_names_;
  192. bool run_only_once_;
  193. std::vector<AnfNodePtr> untyped_nodes_;
  194. bool is_watch_renormalize_;
  195. bool is_enable_;
  196. };
  197. } // namespace opt
  198. } // namespace mindspore
  199. #endif // MINDSPORE_CCSRC_OPTIMIZER_OPTIMIZER_H_