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