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

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