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.

vm.cc 15 kB

5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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/vm.h"
  19. #include <algorithm>
  20. #include "vm/vmimpl.h"
  21. #include "vm/backend.h"
  22. #include "pipeline/jit/parse/data_converter.h"
  23. #include "pybind_api/ir/base_ref_py.h"
  24. namespace mindspore {
  25. namespace compile {
  26. // Initialize StructPartial.
  27. // Arguments:
  28. // fn_: Callable function.
  29. // args_: Sequence of function args.
  30. // fg_: Graph of function.
  31. StructPartial::StructPartial(int64_t fn, const VectorRef &args, const FuncGraphPtr &fg)
  32. : fn_(fn), args_(args), fg_(fg) {}
  33. std::ostream &operator<<(std::ostream &os, const StructPartial &other) {
  34. os << "partial(" << other.fn_ << ", " << other.args_.ToString() << ")";
  35. return os;
  36. }
  37. bool operator==(const StructPartial &lhs, const StructPartial &rhs) {
  38. return (lhs.fn_ == rhs.fn_ && lhs.args_ == rhs.args_ && lhs.fg_ == rhs.fg_);
  39. }
  40. StructSimuSwitch::StructSimuSwitch(const BaseRef &fn, const BaseRef &value) : fn_(fn), value_(value) {}
  41. std::ostream &operator<<(std::ostream &os, const StructSimuSwitch &other) {
  42. os << "SimulSwitch(" << other.fn_.ToString() << ", " << other.value_.ToString() << ")";
  43. return os;
  44. }
  45. bool operator==(const StructSimuSwitch &lhs, const StructSimuSwitch &rhs) {
  46. return (lhs.fn_ == rhs.fn_ && lhs.value_ == rhs.value_);
  47. }
  48. std::ostream &operator<<(std::ostream &os, const SwitchCondStatus &other) {
  49. os << "SwitchCondStatus(" << static_cast<int64_t>(other) << ")";
  50. return os;
  51. }
  52. // Follow the specified instructions to create a VM.
  53. // Arguments:
  54. // insts_: std::vector<std::map<std::string, VectorRef>>
  55. // insts_stack_: The value stack.
  56. // retp_: The call stack.
  57. // pc_: program counter (next instruction)
  58. // sp_: stack pointer (for the value stack)
  59. FinalVM::FinalVM(const InstSet &insts, const BackendPtr &backend) : insts_(insts), pc_(0), sp_(0), backend_(backend) {
  60. MS_LOG(DEBUG) << "InstSet size:" << insts_.size();
  61. insts_stack_.emplace_back(BaseRef());
  62. retp_.push(-1);
  63. }
  64. void FinalVM::Push(const BaseRef &v) {
  65. MS_LOG(DEBUG) << "Push " << v.ToString() << " sp_:" << sp_;
  66. insts_stack_[IntToSize(sp_++)] = v;
  67. }
  68. void FinalVM::Pop(int64_t n) {
  69. if (n > sp_) {
  70. MS_LOG(EXCEPTION) << "Invalid value of n " << n << ", it should be not more than " << sp_ - 1;
  71. }
  72. for (int64_t i = 0; i < n; i++) {
  73. insts_stack_[IntToSize(sp_ - i - 1)] = BaseRef();
  74. }
  75. sp_ -= n;
  76. }
  77. void FinalVM::MoveStack(int64_t nitems, int64_t height) {
  78. if (nitems > height || height > sp_) {
  79. MS_LOG(EXCEPTION) << "MoveStack arg error: nitems=" << nitems << " height=" << height;
  80. }
  81. int64_t n = height - nitems;
  82. int64_t src = sp_ - height;
  83. int64_t dst = sp_ - nitems;
  84. for (int64_t i = 0; i < nitems; i++) {
  85. insts_stack_[IntToSize(src + i)] = insts_stack_[IntToSize(dst + i)];
  86. }
  87. Pop(n);
  88. }
  89. BaseRef FinalVM::Ref(int64_t i) {
  90. MS_LOG(DEBUG) << "Ref i:" << i << " sp_:" << sp_;
  91. size_t sp_next = LongToSize(sp_ + i);
  92. if (sp_next < insts_stack_.size()) {
  93. if (utils::isa<PyObjectRef>(insts_stack_[sp_next])) {
  94. py::object value = utils::cast<PyObjectRef>(insts_stack_[sp_next]).object_;
  95. MS_LOG(DEBUG) << "VM ref python:" << py::str(value);
  96. return parse::data_converter::PyDataToValue(value);
  97. }
  98. MS_LOG(DEBUG) << "Ref not python :" << insts_stack_[sp_next].ToString();
  99. return insts_stack_[sp_next];
  100. }
  101. MS_LOG(EXCEPTION) << "IndexError: index(" << sp_next << ") out of range [0, " << insts_stack_.size() << ").";
  102. }
  103. void FinalVM::Pushp() { retp_.push(pc_); }
  104. void FinalVM::Popp() {
  105. if (retp_.empty()) {
  106. MS_LOG(EXCEPTION) << "Stack retp_ is empty";
  107. }
  108. pc_ = retp_.top();
  109. MS_LOG(DEBUG) << "Pop pc:" << pc_ << ", sp:" << sp_;
  110. retp_.pop();
  111. }
  112. void FinalVM::Pushsp() { retsp_.push(sp_); }
  113. void FinalVM::Popsp() {
  114. int64_t sp = retsp_.top();
  115. MS_LOG(DEBUG) << "Current sp:" << sp_ << ", before sp:" << sp << ", " << sp_ - sp;
  116. if (sp_ >= sp) {
  117. Pop(sp_ - sp + 1);
  118. retsp_.pop();
  119. } else {
  120. MS_LOG(EXCEPTION) << "Stack point sp_:" << sp << " must biger than sp:" << sp_;
  121. }
  122. }
  123. void FinalVM::DoJmp(const BaseRef &jmp_orig) {
  124. MS_LOG(DEBUG) << "Start";
  125. BaseRef jmp = jmp_orig;
  126. if (utils::isa<StructPartial>(jmp)) { // need to inherit from Base
  127. MS_LOG(DEBUG) << "Start jump StructPartial";
  128. auto new_jmp = utils::cast<std::shared_ptr<StructPartial>>(jmp);
  129. auto args = new_jmp->args_;
  130. InstPadStack(VectorRef(std::vector<BaseRef>{static_cast<int64_t>(args.size())}));
  131. auto iter = args.rbegin();
  132. for (; iter != args.rend(); ++iter) {
  133. Push(*iter);
  134. }
  135. pc_ = new_jmp->fn_;
  136. return;
  137. }
  138. if (!utils::isa<int64_t>(jmp)) {
  139. MS_LOG(EXCEPTION) << "Jmp inst should be a int64_t";
  140. }
  141. pc_ = utils::cast<int64_t>(jmp);
  142. MS_LOG(DEBUG) << "End do jump pc_:" << pc_;
  143. }
  144. BaseRef FinalVM::Eval(const VectorRef &args) {
  145. MS_LOG(DEBUG) << "Start: " << args.size();
  146. insts_stack_.clear();
  147. insts_stack_.resize(args.size());
  148. std::stack<int64_t>().swap(retp_);
  149. retp_.push(-1);
  150. pc_ = 0;
  151. sp_ = 0;
  152. auto riter = args.rbegin();
  153. for (; riter != args.rend(); ++riter) {
  154. if (utils::isa<PyObjectRef>(*riter)) {
  155. PyObjectRef py_ref = utils::cast<PyObjectRef>(*riter);
  156. py::object value = py_ref.object_;
  157. if (py::isinstance<py::bool_>(value)) {
  158. auto a = py::cast<bool>(value);
  159. Push(static_cast<int64_t>(a));
  160. continue;
  161. }
  162. }
  163. Push(*riter);
  164. }
  165. while (pc_ >= 0) {
  166. auto inst = insts_[IntToSize(pc_)];
  167. MS_LOG(DEBUG) << "Loop " << insts_.size() << ", pc:" << pc_ << ", inst:" << inst_str[inst.first];
  168. ++pc_;
  169. auto iter = inst_function_map.find(inst.first);
  170. if (iter != inst_function_map.end()) {
  171. iter->second(inst.second);
  172. } else {
  173. MS_LOG(EXCEPTION) << "Unknown instruction {" << inst_str[inst.first] << "}";
  174. }
  175. }
  176. MS_LOG(DEBUG) << "End";
  177. return insts_stack_[0];
  178. }
  179. void FinalVM::InstCall(const VectorRef &args) {
  180. MS_LOG(DEBUG) << "Start";
  181. const size_t args_size = 1;
  182. if (args.size() != args_size) {
  183. MS_LOG(ERROR) << __FUNCTION__ << " requires " << args_size << " parameter, while the input size is " << args.size()
  184. << ".";
  185. return;
  186. }
  187. int64_t jmp = utils::cast<int64_t>(args[0]);
  188. MS_LOG(DEBUG) << "Call pushp:" << pc_ << ", jmp:" << jmp << ", sp:" << sp_;
  189. Pushp();
  190. DoJmp(Ref(jmp));
  191. MS_LOG(DEBUG) << "Instcall end sp :" << sp_;
  192. }
  193. void FinalVM::InstTailCall(const VectorRef &args) {
  194. MS_LOG(DEBUG) << "Start";
  195. const size_t args_size = 3;
  196. if (args.size() != args_size) {
  197. MS_LOG(ERROR) << __FUNCTION__ << " requires " << args_size << " parameters, while the input size is " << args.size()
  198. << ".";
  199. return;
  200. }
  201. int64_t jmp = utils::cast<int64_t>(args[0]);
  202. int64_t height = utils::cast<int64_t>(args[1]);
  203. int64_t nargs = utils::cast<int64_t>(args[2]);
  204. auto new_jmp = Ref(jmp);
  205. MoveStack(nargs, height);
  206. MS_LOG(DEBUG) << "TailCall pushp:" << pc_ << ", jmp:" << jmp;
  207. DoJmp(new_jmp);
  208. MS_LOG(DEBUG) << "End";
  209. }
  210. void FinalVM::InstSwitchReturn(const VectorRef &args) {
  211. MS_LOG(DEBUG) << "Start";
  212. if (args.size() != 1) {
  213. MS_LOG(ERROR) << __FUNCTION__ << " requires one parameter, while the input size is " << args.size() << ".";
  214. return;
  215. }
  216. Pop(1);
  217. Popsp();
  218. }
  219. void FinalVM::InstReturn(const VectorRef &args) {
  220. MS_LOG(DEBUG) << "Start";
  221. const size_t args_size = 2;
  222. if (args.size() != args_size) {
  223. MS_LOG(ERROR) << __FUNCTION__ << " requires " << args_size << " parameters, while the input size is " << args.size()
  224. << ".";
  225. return;
  226. }
  227. int64_t rpos = utils::cast<int64_t>(args[0]);
  228. int64_t height = utils::cast<int64_t>(args[1]);
  229. auto rv = Ref(rpos);
  230. Pop(height);
  231. Push(rv);
  232. Popp();
  233. MS_LOG(DEBUG) << "End";
  234. }
  235. void FinalVM::InstRealPartial(const VectorRef &args) {
  236. const size_t args_size = 1;
  237. if (args.size() < args_size) {
  238. MS_LOG(ERROR) << __FUNCTION__ << " requires " << args_size << " or more parameters, while the input size is "
  239. << args.size() << ".";
  240. return;
  241. }
  242. int64_t fn_ = utils::cast<int64_t>(args[0]);
  243. auto fn = utils::cast<int64_t>(Ref(fn_));
  244. MS_LOG(DEBUG) << "Partial argssize:" << args.size();
  245. std::vector<BaseRef> outs(args.size() - 1);
  246. (void)std::transform(args.begin() + 1, args.end(), outs.begin(),
  247. [&, this](const BaseRef &a) { return Ref(utils::cast<int64_t>(a)); });
  248. Push(std::make_shared<StructPartial>(fn, VectorRef(outs)));
  249. }
  250. void FinalVM::InstPartial(const VectorRef &args) {
  251. MS_LOG(DEBUG) << "Start";
  252. InstRealPartial(args);
  253. MS_LOG(DEBUG) << "End";
  254. }
  255. void FinalVM::InstRealSwitch(const VectorRef &args) {
  256. const size_t args_size = 3;
  257. if (args.size() != args_size) {
  258. MS_LOG(ERROR) << __FUNCTION__ << " requires " << args_size << " parameters, while the input size is " << args.size()
  259. << ".";
  260. return;
  261. }
  262. int64_t cond = utils::cast<int64_t>(args[0]);
  263. int64_t vtrue = utils::cast<int64_t>(args[1]);
  264. int64_t vfalse = utils::cast<int64_t>(args[2]);
  265. BaseRef c = Ref(cond);
  266. MS_LOG(DEBUG) << vtrue << " false:" << vfalse << " InstSwitch: " << c.ToString();
  267. bool bool_value = false;
  268. if (backend_->GetCond(c, &bool_value)) {
  269. MS_LOG(DEBUG) << "Cond:" << bool_value;
  270. if (bool_value) {
  271. Push(Ref(vtrue));
  272. } else {
  273. Push(Ref(vfalse));
  274. }
  275. } else {
  276. MS_LOG(EXCEPTION) << "Not supported type to be casted to bool";
  277. }
  278. }
  279. void FinalVM::InstSwitch(const VectorRef &args) {
  280. MS_LOG(DEBUG) << "Start";
  281. InstRealSwitch(args);
  282. MS_LOG(DEBUG) << "End";
  283. }
  284. void FinalVM::InstSwitchLayer(const VectorRef &args) {
  285. MS_LOG(DEBUG) << "Start";
  286. const size_t args_size = 2;
  287. if (args.size() != args_size) {
  288. MS_LOG(ERROR) << __FUNCTION__ << " requires " << args_size << " parameters, while the input size is " << args.size()
  289. << ".";
  290. return;
  291. }
  292. int64_t idx = utils::cast<int64_t>(args[0]);
  293. VectorRef branches = utils::cast<VectorRef>(Ref(utils::cast<int64_t>(args[1])));
  294. int64_t size = static_cast<int64_t>(branches.size());
  295. BaseRef index = Ref(idx);
  296. int64_t idx_value = 0;
  297. if (!backend_->GetIndex(index, &idx_value)) {
  298. MS_LOG(EXCEPTION) << "Not supported type to be casted to int64_t.";
  299. }
  300. auto ori_value = idx_value;
  301. if (idx_value < 0) {
  302. // Add support negative index range [-size, -1].
  303. idx_value += size;
  304. }
  305. if (idx_value < 0 || idx_value >= size) {
  306. MS_EXCEPTION(IndexError) << __FUNCTION__ << " given index " << ori_value
  307. << " out of range. Please make sure the value "
  308. << "of index in [" << -size << ", " << size << "), and the type is int32.";
  309. }
  310. Push(branches[idx_value]);
  311. MS_LOG(DEBUG) << "End";
  312. }
  313. void FinalVM::InstTuple(const VectorRef &args) {
  314. MS_LOG(DEBUG) << "Start";
  315. VectorRef tuple;
  316. auto iter = args.begin();
  317. for (; iter != args.end(); ++iter) {
  318. auto a = utils::cast<int64_t>(*iter);
  319. tuple.push_back(Ref(a));
  320. }
  321. Push(tuple);
  322. MS_LOG(DEBUG) << "End";
  323. }
  324. void FinalVM::InstPush(const VectorRef &args) {
  325. MS_LOG(DEBUG) << "Start";
  326. const size_t args_size = 1;
  327. if (args.size() != args_size) {
  328. MS_LOG(ERROR) << __FUNCTION__ << " requires " << args_size << " parameter, while the input size is " << args.size()
  329. << ".";
  330. return;
  331. }
  332. auto v = args[0];
  333. Push(v);
  334. MS_LOG(DEBUG) << "End";
  335. }
  336. void FinalVM::InstInput(const VectorRef &args) {
  337. MS_LOG(DEBUG) << "Start";
  338. const size_t args_size = 1;
  339. if (args.size() != args_size) {
  340. MS_LOG(ERROR) << __FUNCTION__ << " requires " << args_size << " parameter, while the input size is " << args.size()
  341. << ".";
  342. return;
  343. }
  344. int64_t rpos = utils::cast<int64_t>(args[0]);
  345. Push(Ref(rpos));
  346. MS_LOG(DEBUG) << "End";
  347. }
  348. void FinalVM::InstPadStack(const VectorRef &args) {
  349. MS_LOG(DEBUG) << "Start";
  350. const size_t args_size = 1;
  351. if (args.size() != args_size) {
  352. MS_LOG(ERROR) << __FUNCTION__ << " requires " << args_size << " parameter, while the input size is " << args.size()
  353. << ".";
  354. return;
  355. }
  356. int64_t sz = utils::cast<int64_t>(args[0]);
  357. MS_LOG(DEBUG) << insts_stack_.size() << " need padstack " << sz << " sp_ " << sp_;
  358. size_t stack_size = insts_stack_.size();
  359. int64_t need = sz - (static_cast<int64_t>(stack_size) - sp_);
  360. if (need > 0) {
  361. MS_LOG(DEBUG) << "InstPadStack resize: size:" << insts_stack_.size() << " need pad:" << need;
  362. insts_stack_.resize(stack_size + IntToSize(need));
  363. }
  364. MS_LOG(DEBUG) << "End";
  365. }
  366. void FinalVM::InstExternal(const VectorRef &args) {
  367. MS_LOG(DEBUG) << "Start:" << args.size();
  368. if (args.empty()) {
  369. MS_LOG(EXCEPTION) << "Args is empty!";
  370. }
  371. VectorRef tuple;
  372. RunFunctionRef run_ref = utils::cast<RunFunctionRef>(args[0]);
  373. compile::RunFuncPtr fn = run_ref.func_;
  374. for (size_t i = 2; i < args.size(); ++i) {
  375. auto index = utils::cast<int64_t>(args[i]);
  376. tuple.push_back(Ref(index));
  377. }
  378. if (!fn) {
  379. MS_LOG(EXCEPTION) << "Function not callable";
  380. }
  381. auto outs = (*fn)(tuple);
  382. MS_LOG(DEBUG) << "'fn' out size:" << outs.size();
  383. for (auto &o : outs) {
  384. MS_LOG(DEBUG) << "InstExternal value:" << o.ToString();
  385. Push(o);
  386. }
  387. MS_LOG(DEBUG) << "End";
  388. }
  389. void FinalVM::InstPushPrim(const VectorRef &args) {
  390. MS_LOG(DEBUG) << "Start: " << args.size();
  391. const size_t args_size = 2;
  392. if (args.size() < args_size) {
  393. MS_LOG(ERROR) << __FUNCTION__ << " requires " << args_size << " or more parameters, while the input size is "
  394. << args.size() << ".";
  395. return;
  396. }
  397. auto prim = utils::cast<PrimitivePtr>(args[0]);
  398. VectorRef tuple;
  399. for (size_t i = 1; i < args.size(); ++i) {
  400. auto index = utils::cast<int64_t>(args[i]);
  401. tuple.push_back(Ref(index));
  402. }
  403. if (prim->name() == "bprop_cut") {
  404. auto outs = RunHook(prim, tuple);
  405. Push(outs);
  406. } else {
  407. auto outs = RunOperation(prim, tuple);
  408. Push(outs);
  409. }
  410. MS_LOG(DEBUG) << "End";
  411. }
  412. void FinalVM::SyncData(const py::object &arg) {
  413. if (py::isinstance<py::tuple>(arg)) {
  414. auto arg_list = py::cast<py::tuple>(arg);
  415. for (size_t i = 0; i < arg_list.size(); i++) {
  416. SyncData(arg_list[i]);
  417. }
  418. }
  419. if (py::isinstance<tensor::Tensor>(arg)) {
  420. auto tensor = py::cast<tensor::TensorPtr>(arg);
  421. (void)tensor->data_sync();
  422. }
  423. }
  424. BaseRef FinalVM::RunHook(const PrimitivePtr &prim, const VectorRef &args) {
  425. MS_LOG(DEBUG) << "input for operation:";
  426. MS_EXCEPTION_IF_NULL(prim);
  427. return prim->RunHookFunction(args);
  428. }
  429. } // namespace compile
  430. } // namespace mindspore