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

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