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