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.3 kB

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