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

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