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.

segment_runner.cc 8.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. /**
  2. * This is the C++ adaptation and derivative work of Myia (https://github.com/mila-iqia/myia/).
  3. *
  4. * Copyright 2019 Huawei Technologies Co., Ltd
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #include "vm/segment_runner.h"
  19. #include <algorithm>
  20. #include <functional>
  21. #include <memory>
  22. #include <set>
  23. #include <tuple>
  24. #include <unordered_map>
  25. #include <utility>
  26. #include <string>
  27. #include "utils/log_adapter.h"
  28. #include "utils/utils.h"
  29. #include "ir/manager.h"
  30. #include "ir/func_graph_cloner.h"
  31. #include "frontend/operator/ops.h"
  32. namespace mindspore {
  33. namespace compile {
  34. // cached conversion
  35. ConvertCache g_ConvertCache;
  36. void ClearConvertCache() { g_ConvertCache.clear(); }
  37. // Return the list of nodes whose values are required beyond this segment.
  38. // Arguments:
  39. // lst: list of nodes (the segment)
  40. // users: dict mapping each node to its users (globally)
  41. // seen: set of nodes that are part of the segment
  42. AnfNodePtrList GetOutput(const AnfNodePtrList &lst, const NodeUsersMap &users, const std::vector<AnfNodePtr> &seen) {
  43. AnfNodePtrList output;
  44. if (users.size() == 0) {
  45. return output;
  46. }
  47. (void)std::transform(
  48. std::begin(lst), std::end(lst), std::back_inserter(output), [&users, &seen](AnfNodePtr n) -> AnfNodePtr {
  49. auto usersn = users.find(n);
  50. bool is_referred_out_of_segment = std::any_of(
  51. std::begin(usersn->second), std::end(usersn->second), [&seen](const std::pair<AnfNodePtr, int64_t> &u) -> bool {
  52. return std::find(std::begin(seen), std::end(seen), u.first) == std::end(seen);
  53. });
  54. if (n->isa<CNode>() && is_referred_out_of_segment) {
  55. return n;
  56. }
  57. return nullptr;
  58. });
  59. // remove nullptr
  60. for (auto it = output.begin(); it != output.end();) {
  61. if (*it == nullptr) {
  62. it = output.erase(it);
  63. } else {
  64. ++it;
  65. }
  66. }
  67. return output;
  68. }
  69. namespace {
  70. AnfNodePtr RefSubGraphNode(const FuncGraphPtr &fg, const AnfNodePtr &node, AnfNodePtrList *const inputs_ptr,
  71. AnfNodePtrToAnfNodePtrMap *eqv_ptr) {
  72. MS_EXCEPTION_IF_NULL(fg);
  73. MS_EXCEPTION_IF_NULL(inputs_ptr);
  74. MS_EXCEPTION_IF_NULL(eqv_ptr);
  75. MS_EXCEPTION_IF_NULL(node);
  76. auto &inputs = *inputs_ptr;
  77. auto &eqv = *eqv_ptr;
  78. if (node->isa<ValueNode>() && !IsValueNode<FuncGraph>(node)) {
  79. eqv[node] = node;
  80. } else if (eqv.find(node) == eqv.end()) {
  81. bool ignore_make_tuple = false;
  82. if (IsPrimitiveCNode(node, prim::kPrimMakeTuple)) {
  83. ignore_make_tuple = true;
  84. auto cnode = node->cast<CNodePtr>();
  85. MS_EXCEPTION_IF_NULL(cnode);
  86. const auto &node_inputs = cnode->inputs();
  87. for (size_t i = 1; i < node_inputs.size(); ++i) {
  88. if (!IsPrimitiveCNode(node_inputs[i], prim::kPrimControlDepend)) {
  89. ignore_make_tuple = false;
  90. break;
  91. }
  92. }
  93. }
  94. if (!ignore_make_tuple) {
  95. inputs.push_back(node);
  96. }
  97. eqv[node] = fg->add_parameter();
  98. eqv[node]->set_abstract(node->abstract());
  99. eqv[node]->set_kernel_info(node->kernel_info_ptr());
  100. }
  101. return eqv[node];
  102. }
  103. } // namespace
  104. std::tuple<FuncGraphPtr, AnfNodePtrList, AnfNodePtrList> TransformSegmentToAnfGraph(const AnfNodePtrList &lst) {
  105. if (lst.empty()) {
  106. MS_LOG(EXCEPTION) << "Input anf node list is empty";
  107. }
  108. TraceManager::DebugTrace(
  109. std::make_shared<TraceSegmentTransform>(lst[0]->cast<CNodePtr>()->func_graph()->debug_info()));
  110. auto fg = std::make_shared<FuncGraph>();
  111. TraceManager::EndTrace();
  112. AnfNodePtrList inputs;
  113. AnfNodePtrToAnfNodePtrMap eqv;
  114. // Merge CNodes into a AnfGraph that represents a linear instruction segment
  115. for (auto n : lst) {
  116. if (!n->isa<CNode>()) {
  117. MS_LOG(EXCEPTION) << "Inst is not CNode";
  118. }
  119. auto &inps = n->cast<CNodePtr>()->inputs();
  120. if (inps.empty()) {
  121. MS_LOG(EXCEPTION) << "Input is empty";
  122. }
  123. if (!IsValueNode<Primitive>(inps[0]) &&
  124. !(IsValueNode<FuncGraph>(inps[0]) &&
  125. inps[0]->cast<ValueNodePtr>()->value()->cast<FuncGraphPtr>()->has_attr(FUNC_GRAPH_ATTR_GRAPH_KERNEL))) {
  126. MS_LOG(EXCEPTION) << "Input[0] Must be a Primitive valuenode";
  127. }
  128. auto fn = inps[0];
  129. std::vector<AnfNodePtr> args{fn};
  130. if (IsPrimitive(fn, prim::kPrimDepend) && inps.size() == 3 && eqv.find(inps[kDependAttachNodeIndex]) == eqv.end()) {
  131. args.emplace_back(RefSubGraphNode(fg, inps[kRealInputIndexInDepend], &inputs, &eqv));
  132. args.emplace_back(NewValueNode(MakeValue(0)));
  133. } else if (IsPrimitive(fn, prim::kPrimControlDepend) && inps.size() == 3) {
  134. for (size_t i = 1; i < inps.size(); ++i) {
  135. if (inps[i]->isa<CNode>() && std::find(lst.begin(), lst.end(), inps[i]) == lst.end()) {
  136. args.emplace_back(NewValueNode(MakeValue(i)));
  137. } else {
  138. args.emplace_back(RefSubGraphNode(fg, inps[i], &inputs, &eqv));
  139. }
  140. }
  141. } else {
  142. (void)std::transform(std::begin(inps) + 1, std::end(inps), std::back_inserter(args),
  143. [&fg, &inputs, &eqv](const AnfNodePtr &a) { return RefSubGraphNode(fg, a, &inputs, &eqv); });
  144. }
  145. TraceManager::DebugTrace(std::make_shared<TraceGetEnv>(n->debug_info()));
  146. eqv[n] = fg->NewCNode(args);
  147. TraceManager::EndTrace();
  148. eqv[n]->set_abstract(n->abstract());
  149. eqv[n]->set_kernel_info(n->kernel_info_ptr());
  150. }
  151. std::vector<AnfNodePtr> eqv_keys;
  152. (void)std::transform(std::begin(eqv), std::end(eqv), std::back_inserter(eqv_keys),
  153. [](const std::pair<AnfNodePtr, AnfNodePtr> &elem) -> AnfNodePtr { return elem.first; });
  154. auto outputs = GetOutput(lst, lst[0]->func_graph()->manager()->node_users(), eqv_keys);
  155. AnfNodePtr fg_output;
  156. if (outputs.size() > 1) {
  157. std::vector<AnfNodePtr> output_args;
  158. output_args.push_back(NewValueNode(prim::kPrimMakeTuple));
  159. (void)std::transform(std::begin(outputs), std::end(outputs), std::back_inserter(output_args),
  160. [&eqv](const AnfNodePtr &o) -> AnfNodePtr { return eqv[o]; });
  161. // Set output for AnfGraph
  162. fg_output = fg->NewCNode(output_args);
  163. } else {
  164. fg_output = eqv[outputs[0]];
  165. }
  166. fg->set_output(fg_output);
  167. return std::make_tuple(fg, inputs, outputs);
  168. }
  169. // Converts the list of nodes to a runnable form.
  170. // All the nodes in the list must represent linear flow (no calls, branches, ...)
  171. // Returns:
  172. // (fn, inputs, outputs):
  173. // - fn: A callable function
  174. // - inputs: the list of inputs nodes whose values should be
  175. // provided to the function
  176. // - outputs: the list of output nodes corresponding to the
  177. // outputs of the function
  178. // Notes:
  179. // This implementation will convert the nodes into a subgraph
  180. // that will run using the MsVM.
  181. template <typename T>
  182. LinConvertResult Convert(const GraphSegmentPtr &segment, const std::string &) {
  183. MS_EXCEPTION_IF_NULL(segment);
  184. auto cached = g_ConvertCache.find(segment);
  185. if (cached != g_ConvertCache.end()) {
  186. return cached->second;
  187. }
  188. LinConvertResult result;
  189. FuncGraphPtr fg = nullptr;
  190. AnfNodePtrList inputs;
  191. AnfNodePtrList outputs;
  192. std::tie(fg, inputs, outputs) = TransformSegmentToAnfGraph(segment->nodes_);
  193. // Clone in case g contains subgraphs that have a different manager
  194. fg = BasicClone(fg);
  195. std::shared_ptr<VMImpl> vm = std::make_shared<T>();
  196. result.run =
  197. std::make_shared<RunFunc>([fg, vm](const VectorRef &args) -> VectorRef { return vm->RunGraph(fg, args); });
  198. result.inputs = inputs;
  199. result.outputs = outputs;
  200. result.graph_id = UINT32_MAX;
  201. (void)g_ConvertCache.emplace(segment, result);
  202. return result;
  203. }
  204. LinkFuncType MsVmConvert = Convert<VM>;
  205. std::set<std::string> backend_list = {
  206. kMsConvert,
  207. kMsVm,
  208. };
  209. } // namespace compile
  210. } // namespace mindspore