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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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->stage() != -1 || 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. class InlinerBase;
  64. using CriterionFuncType = std::function<bool(InlinerBase *, const FuncGraphPtr &, const AnfNodePtr &)>;
  65. bool IsUniqueUse(InlinerBase *, const FuncGraphPtr &fg, const AnfNodePtr &);
  66. bool IsTrivial(InlinerBase *, const FuncGraphPtr &fg, const AnfNodePtr &);
  67. bool IsInside(InlinerBase *, const FuncGraphPtr &, const AnfNodePtr &node);
  68. bool IsCore(InlinerBase *, const FuncGraphPtr &fg, const AnfNodePtr &);
  69. bool IsDirectParentCall(InlinerBase *, const FuncGraphPtr &fg, const AnfNodePtr &node);
  70. bool IsNotRecursive(InlinerBase *inliner, const FuncGraphPtr &fg, const AnfNodePtr &);
  71. // {G, Xs}
  72. class InlinerBase : public AnfVisitor {
  73. public:
  74. explicit InlinerBase(std::vector<std::vector<CriterionFuncType>> criterions, bool use_move = true)
  75. : use_move_(use_move), criterions_(criterions) {}
  76. ~InlinerBase() override = default;
  77. AnfNodePtr operator()(const OptimizerPtr &, const AnfNodePtr &node) override {
  78. if (!node->isa<CNode>()) {
  79. return nullptr;
  80. }
  81. auto &inputs = node->cast<CNodePtr>()->inputs();
  82. if (inputs.size() < 1 || !IsValueNode<FuncGraph>(inputs[0])) {
  83. return nullptr;
  84. }
  85. // G
  86. auto fg = GetValueNode<FuncGraphPtr>(inputs[0]);
  87. if (fg->has_flag(FUNC_GRAPH_FLAG_DEFER_INLINE) || fg->stage() != -1 || fg->stub()) {
  88. return nullptr;
  89. }
  90. // Do not inline GraphKernel to Cell.
  91. if (fg->has_attr(FUNC_GRAPH_ATTR_GRAPH_KERNEL) && !node->func_graph()->has_attr(FUNC_GRAPH_ATTR_GRAPH_KERNEL)) {
  92. // If the GraphKernel only contains a return node, we make it inlined.
  93. if (fg->nodes().size() - fg->parameters().size() > 1) {
  94. return nullptr;
  95. }
  96. }
  97. Reset();
  98. // 'criterions_': {criterion_group_1:{criterion1, criterion2, ...}, criterion_group_2:{...}, ...}
  99. // All the criterions of 'criterion group' are true would set 'criterion group' as 'true'. As [AND].
  100. // Anyone of 'criterion group' in 'criterions_' is 'true' would be matched. As [OR].
  101. bool is_match = false;
  102. for (auto &criterions : criterions_) { // Each 'criterion group' in criterions_.
  103. is_match = true;
  104. for (auto &criterion : criterions) { // Each criterion in 'criterion group'.
  105. if (!criterion(this, fg, node)) {
  106. is_match = false;
  107. break;
  108. }
  109. }
  110. if (is_match) {
  111. break;
  112. }
  113. }
  114. if (!is_match) {
  115. return nullptr;
  116. }
  117. std::vector<AnfNodePtr> args;
  118. (void)std::copy(inputs.begin() + 1, inputs.end(), std::back_inserter(args));
  119. // Compare size to avoid the case that the function has default value after grad.
  120. // for which after renormalize, the function default value will be an input
  121. if (fg->parameters().size() != args.size()) {
  122. return nullptr;
  123. }
  124. if (IsUniqueUse(nullptr, fg, nullptr)) {
  125. // For the single used fg, including non-after and after not matched above,
  126. // we move the whole fg nodes.
  127. if (use_move_) {
  128. auto mng = fg->manager();
  129. MS_EXCEPTION_IF_NULL(mng);
  130. ReplaceParams(mng, args, fg);
  131. auto out_node = fg->output();
  132. mng->MoveAllCNodeDropGraph(fg, node->func_graph(), inputs[0]->scope());
  133. return out_node;
  134. }
  135. // The other branch calling the last after block.
  136. if (fg->has_flag(FUNC_GRAPH_FLAG_AFTER_BLOCK)) {
  137. // Check if parameters' changed.
  138. auto param_simplified_caller = SimplifyAfterParameter(fg, node, args);
  139. if (param_simplified_caller != nullptr) {
  140. return param_simplified_caller;
  141. }
  142. }
  143. } else {
  144. // We don't expand the middle multiple used after block, except the last one.
  145. if (GraphHasBranch(fg)) {
  146. return nullptr;
  147. }
  148. // Check if parameters' changed for the first met branch calling.
  149. if (fg->has_flag(FUNC_GRAPH_FLAG_AFTER_BLOCK)) {
  150. auto param_simplified_caller = SimplifyAfterParameter(fg, node, args);
  151. if (param_simplified_caller != nullptr) {
  152. return param_simplified_caller;
  153. }
  154. }
  155. }
  156. // Or, just make a clone for not single used fg.
  157. return InlineClone(fg, node->func_graph(), args, inputs[0]->scope());
  158. }
  159. void ReplaceParams(const FuncGraphManagerPtr &mng, const std::vector<AnfNodePtr> &new_params,
  160. const FuncGraphPtr &fg) {
  161. auto params = fg->parameters();
  162. auto old_size = params.size();
  163. if (old_size != new_params.size()) {
  164. MS_LOG(EXCEPTION) << "Parameter size not match." << old_size << " new " << new_params.size()
  165. << fg->output()->DebugString(10);
  166. }
  167. for (size_t i = 0; i < old_size; i++) {
  168. (void)mng->Replace(params[i], new_params[i]);
  169. }
  170. }
  171. bool IsRecursive(const FuncGraphPtr &fg) {
  172. if (!is_checked_) {
  173. is_checked_ = true;
  174. is_recursive_ = fg->recursive();
  175. }
  176. return is_recursive_;
  177. }
  178. void Reset() {
  179. is_checked_ = false;
  180. is_recursive_ = false;
  181. }
  182. // For after block which contains branch call, delete the parameters which is not used.
  183. // In most cases, it may be a `Module` or other constant input.
  184. AnfNodePtr SimplifyAfterParameter(const FuncGraphPtr &fg, const AnfNodePtr &node,
  185. const std::vector<AnfNodePtr> &args) {
  186. auto &fg_params = fg->parameters();
  187. std::vector<int64_t> used_param_index;
  188. auto mng = fg->manager();
  189. bool should_simplify = false;
  190. for (size_t i = 0; i < fg_params.size(); i++) {
  191. if (mng->node_users()[fg_params[i]].size() != 0) {
  192. used_param_index.emplace_back(i);
  193. } else {
  194. MS_LOG(DEBUG) << "Not used parameter " << fg_params[i]->DebugString() << " for calling " << fg->ToString();
  195. should_simplify = true;
  196. }
  197. }
  198. if (!should_simplify) {
  199. return nullptr;
  200. }
  201. MS_LOG(DEBUG) << "Parameter not used found for graph :" << fg->ToString();
  202. // Clone a new graph and ignore the not used parameters
  203. auto new_fg = TransformableClone(fg);
  204. auto &new_fg_params = new_fg->parameters();
  205. std::vector<AnfNodePtr> new_params;
  206. std::transform(used_param_index.begin(), used_param_index.end(), std::back_inserter(new_params),
  207. [&new_fg_params](size_t i) { return new_fg_params[i]; });
  208. new_fg->set_parameters(new_params);
  209. std::vector<AnfNodePtr> node_inputs;
  210. node_inputs.push_back(NewValueNode(new_fg));
  211. std::transform(used_param_index.begin(), used_param_index.end(), std::back_inserter(node_inputs),
  212. [&args](size_t i) { return args[i]; });
  213. return node->func_graph()->NewCNode(node_inputs);
  214. }
  215. // This is a try-best algorithm to find a graph which may generate branch call.
  216. // It does not handle high-order function call. For high-orderer call branch, it still may be inlined.
  217. bool GraphHasBranch(FuncGraphPtr fg) {
  218. if (graph_branch_cache_.find(fg) != graph_branch_cache_.end()) {
  219. return graph_branch_cache_[fg];
  220. }
  221. bool has_branch = false;
  222. auto nodes = fg->nodes();
  223. for (auto &item : nodes) {
  224. if (IsPrimitiveCNode(item, prim::kPrimSwitch)) {
  225. auto sw_inputs = item->cast<CNodePtr>()->inputs();
  226. if (sw_inputs.size() != 4) {
  227. MS_LOG(EXCEPTION) << "switch inputs should be 4";
  228. }
  229. if (!sw_inputs[1]->isa<ValueNode>() || IsValueNode<tensor::Tensor>(sw_inputs[1])) {
  230. has_branch = true;
  231. break;
  232. }
  233. } else if (IsCNodeGraph(item)) {
  234. auto cinputs = item->cast<CNodePtr>()->inputs();
  235. if (cinputs.size() < 1) {
  236. MS_LOG(EXCEPTION) << "graph call inputs should greater than 1";
  237. }
  238. FuncGraphPtr call_fg = GetValueNode<FuncGraphPtr>(cinputs[0]);
  239. bool call_fg_has_branch = GraphHasBranch(call_fg);
  240. if (call_fg_has_branch) {
  241. has_branch = true;
  242. break;
  243. }
  244. } else if (IsPrimitiveCNode(item, prim::kPrimPartial)) {
  245. auto cinputs = item->cast<CNodePtr>()->inputs();
  246. if (cinputs.size() < 2) {
  247. MS_LOG(EXCEPTION) << "partial call inputs should greater than 2";
  248. }
  249. FuncGraphPtr call_fg = GetValueNode<FuncGraphPtr>(cinputs[1]);
  250. if (call_fg == nullptr) {
  251. continue;
  252. }
  253. bool call_fg_has_branch = GraphHasBranch(call_fg);
  254. if (call_fg_has_branch) {
  255. has_branch = true;
  256. break;
  257. }
  258. }
  259. }
  260. graph_branch_cache_[fg] = has_branch;
  261. return has_branch;
  262. }
  263. private:
  264. bool is_checked_{false}, is_recursive_{false};
  265. bool use_move_;
  266. std::vector<std::vector<CriterionFuncType>> criterions_;
  267. std::unordered_map<FuncGraphPtr, bool> graph_branch_cache_;
  268. };
  269. bool IsUniqueUse(InlinerBase *, const FuncGraphPtr &fg, const AnfNodePtr &) {
  270. auto &cnodes = fg->func_graph_cnodes_index();
  271. int64_t n_use = std::accumulate(
  272. cnodes.begin(), cnodes.end(), 0,
  273. [](int64_t sum, const std::pair<const CNodeIndexPairPtr, int64_t> &item) { return sum + item.second; });
  274. return n_use == 1;
  275. }
  276. bool IsTrivial(InlinerBase *, const FuncGraphPtr &fg, const AnfNodePtr &) {
  277. auto n_cnode = fg->nodes().size() - fg->parameters().size();
  278. // There is at least one CNode(return, other_node).
  279. return n_cnode <= 2;
  280. }
  281. bool IsInside(InlinerBase *, const FuncGraphPtr &, const AnfNodePtr &node) {
  282. MS_EXCEPTION_IF_NULL(node->func_graph());
  283. return node->func_graph()->has_flag("inline_inside");
  284. }
  285. bool IsCore(InlinerBase *, const FuncGraphPtr &fg, const AnfNodePtr &) { return fg->has_flag("core"); }
  286. bool IsDirectParentCall(InlinerBase *, const FuncGraphPtr &fg, const AnfNodePtr &node) {
  287. bool unique_use = IsUniqueUse(nullptr, fg, nullptr);
  288. bool is_recursive = fg->recursive();
  289. if (fg->parent() != nullptr && is_recursive) {
  290. if (fg->parent() == node->func_graph() && unique_use) {
  291. return true;
  292. }
  293. }
  294. return false;
  295. }
  296. bool IsNotRecursive(InlinerBase *inliner, const FuncGraphPtr &fg, const AnfNodePtr &) {
  297. return !inliner->IsRecursive(fg);
  298. }
  299. class Inliner : public InlinerBase {
  300. public:
  301. explicit Inliner(bool use_move = true)
  302. : InlinerBase(
  303. // Supports AND conditions in one criterion, Ex. {IsUniqueUse, IsNotRecursive}.
  304. {
  305. {IsTrivial},
  306. {IsInside},
  307. {IsCore},
  308. {IsNotRecursive},
  309. {IsDirectParentCall},
  310. },
  311. use_move) {}
  312. ~Inliner() override = default;
  313. };
  314. class DirectInliner : public InlinerBase {
  315. public:
  316. explicit DirectInliner(bool use_move = true)
  317. : InlinerBase(
  318. // Supports AND conditions in one criterion, Ex. {IsUniqueUse, IsNotRecursive}.
  319. {
  320. {IsDirectParentCall},
  321. },
  322. use_move) {}
  323. ~DirectInliner() override = default;
  324. };
  325. } // namespace irpass
  326. } // namespace opt
  327. } // namespace mindspore
  328. #endif // MINDSPORE_CCSRC_FRONTEND_OPTIMIZER_IRPASS_INLINE_H_