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.

vmimpl.cc 14 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /**
  2. * This is the C++ adaptation and derivative work of Myia (https://github.com/mila-iqia/myia/).
  3. *
  4. * Copyright 2019-2020 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/vmimpl.h"
  19. #include <algorithm>
  20. #include <exception>
  21. #include <vector>
  22. #include <memory>
  23. #include "frontend/operator/ops.h"
  24. #include "ir/manager.h"
  25. #include "ir/func_graph_cloner.h"
  26. #include "utils/convert_utils.h"
  27. #include "utils/primitive_utils.h"
  28. namespace mindspore {
  29. namespace compile {
  30. // Indicate a call to a new frame.
  31. struct CallWrap : public Base {
  32. explicit CallWrap(const VMFramePtr &vm_frame) : frame(vm_frame) {}
  33. VMFramePtr frame{nullptr};
  34. };
  35. using CallWrapPtr = std::shared_ptr<CallWrap>;
  36. // Indicates a return with its value.
  37. struct ReturnWrap : public Base {
  38. explicit ReturnWrap(const BaseRef &r_value) : value(r_value) {}
  39. BaseRef value{BaseRef()};
  40. };
  41. using ReturnWrapPtr = std::shared_ptr<ReturnWrap>;
  42. VMFrame::VMFrame(const AnfNodePtrList &nodes, const AnfNodePtrToBaseRefMap &values,
  43. const AnfNodePtrToBaseRefMap &closure)
  44. : values_(values), todo_(nodes), closure_(closure) {
  45. std::reverse(std::begin(todo_), std::end(todo_));
  46. }
  47. const BaseRef VMFrame::operator[](const AnfNodePtr &node) {
  48. MS_EXCEPTION_IF_NULL(node);
  49. auto ret = values_.find(node);
  50. if (ret != values_.end()) {
  51. return ret->second;
  52. }
  53. ret = closure_.find(node);
  54. if (ret != closure_.end()) {
  55. return ret->second;
  56. }
  57. if (node->isa<ValueNode>()) {
  58. return GetValueNode(node);
  59. }
  60. MS_LOG(EXCEPTION) << "ValueError " << node->type_name();
  61. }
  62. Closure::Closure(const FuncGraphPtr &graph, const AnfNodePtrToBaseRefMap &values)
  63. : func_graph_(graph), values_(values) {}
  64. BaseRef Closure::operator()(const VectorRef &args) {
  65. MS_LOG(DEBUG) << "start closure";
  66. return vm_->Evaluate(func_graph_, args, values_);
  67. }
  68. Partial::Partial(const BaseRef &fn, const VectorRef &args, const VMPtr &vm) : fn_(fn), args_(args), vm_(vm) {}
  69. BaseRef Partial::operator()(const VectorRef &nodes) {
  70. VectorRef arglist;
  71. (void)arglist.insert(arglist.end(), args_.begin(), args_.end());
  72. (void)arglist.insert(arglist.end(), nodes.begin(), nodes.end());
  73. return vm_->Call(fn_, arglist);
  74. }
  75. SetRef VM::ComputeFvs(const FuncGraphPtr &graph) {
  76. MS_EXCEPTION_IF_NULL(graph);
  77. SetRef rval;
  78. for (auto &fkv : graph->free_variables_total()) {
  79. if (utils::isa<FuncGraphPtr>(fkv.first)) {
  80. // Add all value_nodes of g that refer to a fv graph
  81. auto g = utils::cast<FuncGraphPtr>(fkv.first);
  82. for (auto &ctkv : g->value_nodes()) {
  83. auto ct = ctkv.first;
  84. if (GetValueNode(ct) == g) {
  85. (void)rval.insert(ct);
  86. }
  87. }
  88. } else {
  89. // Add a normal fv
  90. (void)rval.insert(fkv.first);
  91. }
  92. }
  93. return rval;
  94. }
  95. void VM::AcquireGraph(const FuncGraphPtr &graph) {
  96. // Already acquired
  97. if (vars_.find(graph) != vars_.end()) {
  98. return;
  99. }
  100. // Add g to manager
  101. manager_->AddFuncGraph(graph);
  102. // Compute fvs for all acquired graph
  103. auto graphs = graph->manager()->func_graphs();
  104. for (auto g = graphs.begin(); g != graphs.end(); ++g) {
  105. vars_[*g] = ComputeFvs(*g);
  106. }
  107. }
  108. VectorRef VM::ExportSequence(const VectorRef &seq) {
  109. std::vector<BaseRef> ret;
  110. (void)std::transform(std::begin(seq), std::end(seq), std::back_inserter(ret),
  111. [&, this](const BaseRef &x) -> BaseRef { return Export(x); });
  112. return VectorRef(ret);
  113. }
  114. ClosurePtr VM::ExportClosure(const ClosurePtr &clos) {
  115. MS_EXCEPTION_IF_NULL(clos);
  116. clos->set_vm(shared_from_this());
  117. return clos;
  118. }
  119. // transform graph to executable closure
  120. ClosurePtr VM::ExportGraph(const FuncGraphPtr &g) {
  121. auto c = std::make_shared<Closure>(g, AnfNodePtrToBaseRefMap());
  122. MS_EXCEPTION_IF_NULL(c);
  123. c->set_vm(shared_from_this());
  124. return c;
  125. }
  126. BaseRef VM::ExportObj(const BaseRef &obj) const { return obj; }
  127. BaseRef VM::Export(const BaseRef &value) {
  128. if (utils::isa<ValuePtr>(value) && utils::cast<ValuePtr>(value)->isa<FuncGraph>()) {
  129. return ExportGraph(utils::cast<ValuePtr>(value)->cast<FuncGraphPtr>());
  130. }
  131. if (utils::isa<ValuePtr>(value) && utils::cast<ValuePtr>(value)->isa<Primitive>()) {
  132. return ExportPrimitive(utils::cast<ValuePtr>(value)->cast<PrimitivePtr>());
  133. }
  134. if (utils::isa<FuncGraphPtr>(value)) {
  135. return ExportGraph(utils::cast<FuncGraphPtr>(value));
  136. }
  137. if (utils::isa<ClosurePtr>(value)) {
  138. return ExportClosure(utils::cast<ClosurePtr>(value));
  139. }
  140. if (utils::isa<PrimitivePtr>(value)) {
  141. return ExportPrimitive(utils::cast<PrimitivePtr>(value));
  142. }
  143. if (utils::isa<VectorRef>(value)) {
  144. return ExportSequence(utils::cast<VectorRef>(value));
  145. }
  146. return ExportObj(value);
  147. }
  148. // Run a graph.
  149. // This will evaluate the passed-in graph and return the resulting value.
  150. BaseRef VM::Evaluate(const FuncGraphPtr &graph, const VectorRef &args, const AnfNodePtrToBaseRefMap &closure) {
  151. AcquireGraph(graph);
  152. MS_LOG(DEBUG) << "evalue arg size: " << args.size();
  153. if (args.size() != graph->parameters().size()) {
  154. MS_LOG(EXCEPTION) << "Call with wrong number of arguments, expect " << graph->parameters().size() << ", but got "
  155. << args.size();
  156. }
  157. // toposort graph nodes, the order will be reversed by frame so that the dependent be computed first
  158. auto nodes = TopoSort(graph->get_return(), SuccVm(graph));
  159. // mapping parameters to args
  160. AnfNodePtrToBaseRefMap values;
  161. for (size_t i = 0; i < args.size(); i++) {
  162. values[graph->parameters()[i]] = args[i];
  163. }
  164. // create top frame with params initialized
  165. VMFramePtrList frames{std::make_shared<VMFrame>(nodes, values, closure)};
  166. // execute frames starting from top frame
  167. while (!frames.empty()) {
  168. auto frame = frames[frames.size() - 1];
  169. auto todo = frame->todo();
  170. while (!todo.empty()) {
  171. auto except = HandleNode(todo[todo.size() - 1], frame);
  172. if (utils::isa<CallWrapPtr>(except)) {
  173. if (todo.size() == 2) {
  174. // The last element is always a return, replace the ret with call frame
  175. frames[frames.size() - 1] = utils::cast<CallWrapPtr>(except)->frame;
  176. } else {
  177. frames.push_back(utils::cast<CallWrapPtr>(except)->frame);
  178. }
  179. break;
  180. }
  181. if (utils::isa<ReturnWrapPtr>(except)) {
  182. (void)frames.erase(frames.begin() + (static_cast<ssize_t>(frames.size()) - 1));
  183. if (frames.size() > 0) {
  184. auto top = frames[frames.size() - 1];
  185. auto td = top->todo();
  186. // set value for top frame's last evaluated node
  187. if (td.empty()) {
  188. MS_LOG(EXCEPTION) << "The td is empty";
  189. }
  190. top->values()[td[td.size() - 1]] = utils::cast<ReturnWrapPtr>(except)->value;
  191. (void)td.erase(td.begin() + (static_cast<ssize_t>(td.size()) - 1));
  192. } else {
  193. return Export(utils::cast<ReturnWrapPtr>(except)->value);
  194. }
  195. break;
  196. }
  197. (void)todo.erase(todo.begin() + (static_cast<ssize_t>(todo.size()) - 1));
  198. }
  199. }
  200. MS_LOG(EXCEPTION) << "VM Evaluate error";
  201. }
  202. SuccFunc VM::SuccVm(const FuncGraphPtr &graph) {
  203. auto fn = [&, this](const AnfNodePtr &node) -> AnfNodePtrList {
  204. MS_EXCEPTION_IF_NULL(node);
  205. AnfNodePtrList ret;
  206. // Follow node.incoming
  207. if (node->isa<CNode>()) {
  208. auto &inputs = node->cast<CNodePtr>()->inputs();
  209. for (auto &i : inputs) {
  210. if (i->func_graph() == node->func_graph() ||
  211. (IsValueNode<FuncGraph>(i) && GetValueNode<FuncGraphPtr>(i)->parent() == graph)) {
  212. ret.push_back(i);
  213. }
  214. }
  215. }
  216. // for subgraph input, add their fvs as succ nodes
  217. if (IsValueNode<FuncGraph>(node) && GetValueNode<FuncGraphPtr>(node)->parent() == graph) {
  218. auto fvs = utils::cast<SetRef>(vars_[GetValueNode<FuncGraphPtr>(node)]);
  219. (void)std::transform(fvs.begin(), fvs.end(), std::back_inserter(ret),
  220. [](const BaseRef &value) -> AnfNodePtr { return utils::cast<AnfNodePtr>(value); });
  221. }
  222. return ret;
  223. };
  224. return fn;
  225. }
  226. BaseRef VM::Call(const BaseRef &fn, const VectorRef &args) {
  227. if (utils::isa<PrimitivePtr>(fn)) {
  228. return RunOperation(utils::cast<PrimitivePtr>(fn), args);
  229. }
  230. if (utils::isa<FuncGraphPtr>(fn)) {
  231. return Evaluate(utils::cast<FuncGraphPtr>(fn), args);
  232. }
  233. if (utils::isa<ClosurePtr>(fn)) {
  234. auto clos = utils::cast<ClosurePtr>(fn);
  235. return Evaluate(clos->func_graph(), args, clos->values());
  236. }
  237. MS_LOG(EXCEPTION) << "Can't call fn";
  238. }
  239. // make call frame for graph
  240. BaseRef VM::_Call(const BaseRef &graph, const VectorRef &args) {
  241. AnfNodePtrToBaseRefMap clos;
  242. auto func_graph = graph;
  243. if (utils::isa<ClosurePtr>(func_graph)) {
  244. clos = utils::cast<ClosurePtr>(func_graph)->values();
  245. func_graph = utils::cast<ClosurePtr>(func_graph)->func_graph();
  246. }
  247. if (utils::isa<ValuePtr>(func_graph)) {
  248. func_graph = utils::cast<ValuePtr>(func_graph)->cast<FuncGraphPtr>();
  249. }
  250. if (!utils::isa<FuncGraphPtr>(func_graph)) {
  251. MS_LOG(EXCEPTION) << "Graph type error";
  252. }
  253. auto graphPtr = utils::cast<FuncGraphPtr>(func_graph);
  254. if (vars_.find(graphPtr) == vars_.end()) {
  255. AcquireGraph(graphPtr);
  256. }
  257. if (args.size() != graphPtr->parameters().size()) {
  258. MS_LOG(EXCEPTION) << "Call with wrong number of arguments, expect " << graphPtr->parameters().size() << ", but got "
  259. << args.size();
  260. }
  261. auto nodes = TopoSort(graphPtr->get_return(), SuccVm(graphPtr));
  262. AnfNodePtrToBaseRefMap values;
  263. for (size_t i = 0; i < args.size(); i++) {
  264. values[graphPtr->parameters()[i]] = args[i];
  265. }
  266. return std::make_shared<CallWrap>(std::make_shared<VMFrame>(nodes, values, clos));
  267. }
  268. // make closure out of graph with fv values from frame
  269. ClosurePtr VM::MakeClosure(const FuncGraphPtr &graph, const VMFramePtr &frame) {
  270. MS_EXCEPTION_IF_NULL(frame);
  271. AnfNodePtrToBaseRefMap clos;
  272. for (auto &v : utils::cast<SetRef>(vars_[graph])) {
  273. auto anf = utils::cast<AnfNodePtr>(v);
  274. clos[anf] = (*frame)[anf];
  275. }
  276. return std::make_shared<Closure>(graph, clos);
  277. }
  278. BaseRef VM::DispatchCall(const AnfNodePtr &node, const VMFramePtr &frame, const BaseRef &fn, const VectorRef &args) {
  279. if (utils::isa<ValuePtr>(fn) && utils::cast<ValuePtr>(fn)->isa<Primitive>()) {
  280. auto fnval = utils::cast<ValuePtr>(fn)->cast<PrimitivePtr>();
  281. MS_LOG(DEBUG) << "DispatchCall prim:" << fnval->name() << ", node:" << node->DebugString(true);
  282. if (args.empty()) {
  283. MS_LOG(EXCEPTION) << "args is empty";
  284. }
  285. if (fnval == prim::kPrimReturn) {
  286. MS_LOG(DEBUG) << "return args:" << args.size();
  287. return std::make_shared<ReturnWrap>(args[0]);
  288. }
  289. if (fnval == prim::kPrimMakeTuple) {
  290. frame->values()[node] = args;
  291. return BaseRef();
  292. }
  293. if (fnval == prim::kPrimPartial) {
  294. VectorRef partial_args(args.begin() + 1, args.end());
  295. frame->values()[node] = (std::make_shared<Partial>(args[0], partial_args, shared_from_this()));
  296. return BaseRef();
  297. }
  298. // call prim implementation
  299. frame->values()[node] = RunOperation(fnval, args);
  300. return BaseRef();
  301. }
  302. // partial args logic
  303. if (utils::isa<PartialPtr>(fn)) {
  304. auto fnPtr = utils::cast<PartialPtr>(fn);
  305. VectorRef arglist;
  306. (void)arglist.insert(arglist.end(), fnPtr->args().begin(), fnPtr->args().end());
  307. (void)arglist.insert(arglist.end(), args.begin(), args.end());
  308. auto ret = DispatchCall(node, frame, fnPtr->fn(), arglist);
  309. if (utils::isa<CallWrapPtr>(ret) || utils::isa<ReturnWrapPtr>(ret)) {
  310. return ret;
  311. }
  312. }
  313. // create frame for graph and closure
  314. if ((utils::isa<ValuePtr>(fn) && utils::cast<ValuePtr>(fn)->isa<FuncGraph>()) || utils::isa<ClosurePtr>(fn)) {
  315. auto ret = _Call(fn, args);
  316. if (utils::isa<CallWrapPtr>(ret) || utils::isa<ReturnWrapPtr>(ret)) {
  317. return ret;
  318. }
  319. }
  320. MS_LOG(EXCEPTION) << "Invalid fn to call";
  321. }
  322. BaseRef VM::HandleNode(const AnfNodePtr &node, const VMFramePtr &frame) {
  323. MS_EXCEPTION_IF_NULL(node);
  324. if (node->isa<Parameter>()) {
  325. // pass
  326. return BaseRef();
  327. }
  328. if (node->isa<ValueNode>()) {
  329. // We only visit valuenode graphs
  330. if (!IsValueNode<FuncGraph>(node)) {
  331. MS_LOG(EXCEPTION) << "We only visit valuenode graphs ";
  332. }
  333. auto g = GetValueNode<FuncGraphPtr>(node);
  334. // if g is a graph with fvs, we need to make a closure for it
  335. auto iterG = vars_.find(g);
  336. if (iterG != vars_.end() && utils::cast<SetRef>(iterG->second).size() != 0) {
  337. frame->values()[node] = MakeClosure(g, frame);
  338. }
  339. return BaseRef();
  340. }
  341. if (node->isa<CNode>()) {
  342. std::vector<BaseRef> fnArgs;
  343. auto &inputs = node->cast<CNodePtr>()->inputs();
  344. // set args' values in frame
  345. (void)std::transform(std::begin(inputs), std::end(inputs), std::back_inserter(fnArgs),
  346. [&](const AnfNodePtr &inp) -> BaseRef { return (*frame)[inp]; });
  347. if (fnArgs.empty()) {
  348. MS_LOG(EXCEPTION) << "function arguments is empty";
  349. } else {
  350. auto args = VectorRef(fnArgs.begin() + 1, fnArgs.end());
  351. auto except = DispatchCall(node, frame, fnArgs[0], args);
  352. return except;
  353. }
  354. }
  355. MS_LOG(EXCEPTION) << "Unknown node type";
  356. }
  357. VectorRef VM::RunGraph(const FuncGraphPtr &g, const VectorRef &args) {
  358. this->manager_ = Manage(g);
  359. auto fn = utils::cast<ClosurePtr>(Export(g));
  360. auto result = (*fn)(args);
  361. if (utils::isa<VectorRef>(result)) {
  362. return utils::cast<VectorRef>(result);
  363. } else {
  364. VectorRef ret({result});
  365. return ret;
  366. }
  367. }
  368. BaseRef RunOperation(const PrimitivePtr &prim, const VectorRef &args) {
  369. MS_LOG(DEBUG) << "operation start " << prim->name();
  370. MS_EXCEPTION_IF_NULL(prim);
  371. auto result = prim->RunComputeFunction(args);
  372. if (result.is_null()) {
  373. return RunComputeFunction(prim, args);
  374. }
  375. return result;
  376. }
  377. } // namespace compile
  378. } // namespace mindspore