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

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