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.

inline.h 11 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. /**
  2. * Copyright 2020 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_FRONTEND_OPTIMIZER_IRPASS_INLINE_H_
  17. #define MINDSPORE_CCSRC_FRONTEND_OPTIMIZER_IRPASS_INLINE_H_
  18. #include <vector>
  19. #include <utility>
  20. #include <algorithm>
  21. #include <unordered_map>
  22. #include "frontend/optimizer/irpass.h"
  23. #include "frontend/optimizer/optimizer.h"
  24. #include "frontend/optimizer/anf_visitor.h"
  25. #include "ir/func_graph.h"
  26. #include "ir/func_graph_cloner.h"
  27. #include "ir/tensor.h"
  28. #include "frontend/operator/ops.h"
  29. namespace mindspore {
  30. namespace opt {
  31. namespace irpass {
  32. class ReplaceApplicator : public AnfVisitor {
  33. public:
  34. AnfNodePtr operator()(const OptimizerPtr &, const AnfNodePtr &node) override {
  35. if (!IsValueNode<FuncGraph>(node)) {
  36. return nullptr;
  37. }
  38. auto fg = GetValueNode<FuncGraphPtr>(node);
  39. if (fg->has_flag(FUNC_GRAPH_FLAG_DEFER_INLINE) || fg->stub() || *(fg->switch_layer_input())) {
  40. return nullptr;
  41. }
  42. auto out = fg->output();
  43. MS_EXCEPTION_IF_NULL(out);
  44. if (!out->isa<CNode>()) {
  45. return nullptr;
  46. }
  47. auto &inputs = out->cast<CNodePtr>()->inputs();
  48. auto params = fg->parameters();
  49. // Exclude first elements of inputs which is fn.
  50. auto input_size = inputs.size();
  51. auto param_size = params.size();
  52. if ((input_size == 1 && param_size == 0) || (input_size > 1 && (input_size - 1) == param_size &&
  53. std::equal(inputs.begin() + 1, inputs.end(), params.begin()))) {
  54. auto inner = inputs[0];
  55. if (IsValueNode<Primitive>(inner) ||
  56. (IsValueNode<FuncGraph>(inner) && GetValueNode<FuncGraphPtr>(inner)->parent() == nullptr)) {
  57. return inner;
  58. }
  59. }
  60. return nullptr;
  61. }
  62. };
  63. using CriterionFuncType = std::function<bool(FuncGraphPtr, AnfNodePtr)>;
  64. bool IsTrivial(const FuncGraphPtr &fg, AnfNodePtr) {
  65. auto n_cnode = fg->nodes().size() - fg->parameters().size();
  66. // There is at least one CNode(return, other_node).
  67. return n_cnode <= 2;
  68. }
  69. bool IsUniqueUse(const FuncGraphPtr &fg, AnfNodePtr) {
  70. auto &cnodes = fg->func_graph_cnodes_index();
  71. int n_use =
  72. std::accumulate(cnodes.begin(), cnodes.end(), 0,
  73. [](int sum, const std::pair<const CNodeIndexPairPtr, int> &item) { return sum + item.second; });
  74. return n_use == 1;
  75. }
  76. bool IsInside(FuncGraphPtr, const AnfNodePtr &node) {
  77. MS_EXCEPTION_IF_NULL(node->func_graph());
  78. return node->func_graph()->has_flag("inline_inside");
  79. }
  80. bool IsCore(const FuncGraphPtr &fg, AnfNodePtr) { return fg->has_flag("core"); }
  81. bool NoCriterion(FuncGraphPtr, AnfNodePtr) { return true; }
  82. bool IsDirectParentCall(FuncGraphPtr fg, AnfNodePtr node) {
  83. bool unique_use = IsUniqueUse(fg, nullptr);
  84. bool is_recursive = fg->recursive();
  85. if (fg->parent() != nullptr && is_recursive) {
  86. if (fg->parent() == node->func_graph() && unique_use) {
  87. return true;
  88. }
  89. }
  90. return false;
  91. }
  92. // {G, Xs}
  93. class InlinerBase : public AnfVisitor {
  94. public:
  95. explicit InlinerBase(std::vector<std::pair<CriterionFuncType, bool>> criterions, bool use_move = true)
  96. : use_move_(use_move), criterions_(criterions) {}
  97. ~InlinerBase() override = default;
  98. AnfNodePtr operator()(const OptimizerPtr &, const AnfNodePtr &node) override {
  99. if (!node->isa<CNode>()) {
  100. return nullptr;
  101. }
  102. auto &inputs = node->cast<CNodePtr>()->inputs();
  103. if (inputs.size() < 1 || !IsValueNode<FuncGraph>(inputs[0])) {
  104. return nullptr;
  105. }
  106. // G
  107. auto fg = GetValueNode<FuncGraphPtr>(inputs[0]);
  108. if (fg->has_flag(FUNC_GRAPH_FLAG_DEFER_INLINE) || fg->stub()) {
  109. return nullptr;
  110. }
  111. // Do not inline GraphKernel to Cell.
  112. if (fg->has_attr(FUNC_GRAPH_ATTR_GRAPH_KERNEL) && !node->func_graph()->has_attr(FUNC_GRAPH_ATTR_GRAPH_KERNEL)) {
  113. // If the GraphKernel only contains a return node, we make it inlined.
  114. if (fg->nodes().size() - fg->parameters().size() > 1) {
  115. return nullptr;
  116. }
  117. }
  118. Reset();
  119. bool is_match = false;
  120. for (auto &criterion : criterions_) {
  121. if (!criterion.first(fg, node)) {
  122. continue;
  123. }
  124. if (criterion.second && IsRecursive(fg)) {
  125. continue;
  126. }
  127. is_match = true;
  128. break;
  129. }
  130. if (!is_match) {
  131. return nullptr;
  132. }
  133. std::vector<AnfNodePtr> args;
  134. (void)std::copy(inputs.begin() + 1, inputs.end(), std::back_inserter(args));
  135. // compare size to avoid the case that the function has default value after grad.
  136. // for which after renormalize, the function default value will be an input
  137. if (fg->parameters().size() != args.size()) {
  138. return nullptr;
  139. }
  140. // Not to inline after block if it has switch call inside, to avoid switch expansion.
  141. if (fg->has_flag(FUNC_GRAPH_FLAG_AFTER_BLOCK)) {
  142. auto has_branch_call = GraphHasBranch(fg);
  143. if (has_branch_call) {
  144. return TransformBranchCall(fg, node, args);
  145. }
  146. }
  147. if (use_move_ && IsUniqueUse(fg, nullptr)) {
  148. auto mng = fg->manager();
  149. MS_EXCEPTION_IF_NULL(mng);
  150. ReplaceParams(mng, args, fg);
  151. auto out_node = fg->output();
  152. mng->MoveAllCNodeDropGraph(fg, node->func_graph(), inputs[0]->scope());
  153. return out_node;
  154. }
  155. return InlineClone(fg, node->func_graph(), args, inputs[0]->scope());
  156. }
  157. void ReplaceParams(const FuncGraphManagerPtr &mng, const std::vector<AnfNodePtr> &new_params,
  158. const FuncGraphPtr &fg) {
  159. auto params = fg->parameters();
  160. auto old_size = params.size();
  161. if (old_size != new_params.size()) {
  162. MS_LOG(EXCEPTION) << "Parameter size not match." << old_size << " new " << new_params.size()
  163. << fg->output()->DebugString(10);
  164. }
  165. for (size_t i = 0; i < old_size; i++) {
  166. (void)mng->Replace(params[i], new_params[i]);
  167. }
  168. }
  169. bool IsRecursive(const FuncGraphPtr &fg) {
  170. if (!is_checked_) {
  171. is_checked_ = true;
  172. is_recursive_ = fg->recursive();
  173. }
  174. return is_recursive_;
  175. }
  176. void Reset() {
  177. is_checked_ = false;
  178. is_recursive_ = false;
  179. }
  180. // For after block which contains branch call, delete the parameters which is not used.
  181. // In most cases, it may be a `Module` or other constant input.
  182. AnfNodePtr TransformBranchCall(const FuncGraphPtr &fg, const AnfNodePtr &node, const std::vector<AnfNodePtr> &args) {
  183. auto &fg_params = fg->parameters();
  184. std::vector<int> used_param_index;
  185. auto mng = fg->manager();
  186. for (size_t i = 0; i < fg_params.size(); i++) {
  187. if (mng->node_users()[fg_params[i]].size() != 0) {
  188. used_param_index.emplace_back(i);
  189. }
  190. }
  191. if (used_param_index.size() != fg_params.size()) {
  192. MS_LOG(DEBUG) << "Parameter not used found for graph :" << fg->ToString();
  193. // clone a new graph and ignore the not used parameters
  194. FuncGraphPtr new_fg = TransformableClone(fg);
  195. auto &new_fg_params = new_fg->parameters();
  196. std::vector<AnfNodePtr> new_params;
  197. std::transform(used_param_index.begin(), used_param_index.end(), std::back_inserter(new_params),
  198. [&new_fg_params](size_t i) { return new_fg_params[i]; });
  199. new_fg->set_parameters(new_params);
  200. std::vector<AnfNodePtr> node_inputs;
  201. node_inputs.push_back(NewValueNode(new_fg));
  202. std::transform(used_param_index.begin(), used_param_index.end(), std::back_inserter(node_inputs),
  203. [&args](size_t i) { return args[i]; });
  204. return node->func_graph()->NewCNode(node_inputs);
  205. }
  206. return nullptr;
  207. }
  208. // This is a try-best algorithm to find a graph which may generate branch call.
  209. // It does not handle high-order function call. For high-orderer call branch, it still may be inlined.
  210. bool GraphHasBranch(FuncGraphPtr fg) {
  211. if (graph_branch_cache_.find(fg) != graph_branch_cache_.end()) {
  212. return graph_branch_cache_[fg];
  213. }
  214. bool has_branch = false;
  215. auto nodes = fg->nodes();
  216. for (auto &item : nodes) {
  217. if (IsPrimitiveCNode(item, prim::kPrimSwitch)) {
  218. auto sw_inputs = item->cast<CNodePtr>()->inputs();
  219. if (sw_inputs.size() != 4) {
  220. MS_LOG(EXCEPTION) << "switch inputs should be 4";
  221. }
  222. if (!sw_inputs[1]->isa<ValueNode>() || IsValueNode<tensor::Tensor>(sw_inputs[1])) {
  223. has_branch = true;
  224. break;
  225. }
  226. } else if (IsCNodeGraph(item)) {
  227. auto cinputs = item->cast<CNodePtr>()->inputs();
  228. if (cinputs.size() < 1) {
  229. MS_LOG(EXCEPTION) << "graph call inputs should greater than 1";
  230. }
  231. FuncGraphPtr call_fg = GetValueNode<FuncGraphPtr>(cinputs[0]);
  232. bool call_fg_has_branch = GraphHasBranch(call_fg);
  233. if (call_fg_has_branch) {
  234. has_branch = true;
  235. break;
  236. }
  237. } else if (IsPrimitiveCNode(item, prim::kPrimPartial)) {
  238. auto cinputs = item->cast<CNodePtr>()->inputs();
  239. if (cinputs.size() < 2) {
  240. MS_LOG(EXCEPTION) << "partial call inputs should greater than 2";
  241. }
  242. FuncGraphPtr call_fg = GetValueNode<FuncGraphPtr>(cinputs[1]);
  243. if (call_fg == nullptr) {
  244. continue;
  245. }
  246. bool call_fg_has_branch = GraphHasBranch(call_fg);
  247. if (call_fg_has_branch) {
  248. has_branch = true;
  249. break;
  250. }
  251. }
  252. }
  253. graph_branch_cache_[fg] = has_branch;
  254. return has_branch;
  255. }
  256. private:
  257. bool is_checked_{false}, is_recursive_{false};
  258. bool use_move_;
  259. std::vector<std::pair<CriterionFuncType, bool>> criterions_;
  260. std::unordered_map<FuncGraphPtr, bool> graph_branch_cache_;
  261. };
  262. class Inliner : public InlinerBase {
  263. public:
  264. explicit Inliner(bool use_move = true)
  265. : InlinerBase(
  266. {
  267. {IsUniqueUse, true},
  268. {IsTrivial, false},
  269. {IsInside, false},
  270. {IsCore, false},
  271. {IsDirectParentCall, false},
  272. {NoCriterion, true},
  273. },
  274. use_move) {}
  275. ~Inliner() override = default;
  276. };
  277. class DirectInliner : public InlinerBase {
  278. public:
  279. explicit DirectInliner(bool use_move = true)
  280. : InlinerBase(
  281. {
  282. {IsDirectParentCall, false},
  283. },
  284. use_move) {}
  285. ~DirectInliner() override = default;
  286. };
  287. } // namespace irpass
  288. } // namespace opt
  289. } // namespace mindspore
  290. #endif // MINDSPORE_CCSRC_FRONTEND_OPTIMIZER_IRPASS_INLINE_H_