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.

interpreter_impl.cpp 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. /**
  2. * \file imperative/src/impl/interpreter_impl.cpp
  3. * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  4. *
  5. * Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  6. *
  7. * Unless required by applicable law or agreed to in writing,
  8. * software distributed under the License is distributed on an
  9. * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. */
  11. #include "./interpreter_impl.h"
  12. #include "megbrain/common.h"
  13. using namespace mgb;
  14. using namespace imperative;
  15. using namespace interpreter;
  16. using namespace interpreter::intl;
  17. std::unique_ptr<Interpreter::Channel> InterpreterImpl::create_channel() {
  18. return std::make_unique<ChannelImpl>();
  19. }
  20. Interpreter& Interpreter::inst() {
  21. static InterpreterImpl inst_;
  22. return inst_;
  23. }
  24. void* ChannelImpl::put(const HostTensorND& value) {
  25. auto info = alloc();
  26. info->desc.layout = value.layout();
  27. info->desc.comp_node = value.comp_node();
  28. info->desc.value = value.proxy_to_default_cpu();
  29. m_valid_handle.insert(info);
  30. m_worker.add_task(Put{info, value});
  31. return info;
  32. }
  33. void* ChannelImpl::put(const DeviceTensorND& data) {
  34. auto info = alloc();
  35. info->desc.layout = data.layout();
  36. info->desc.comp_node = data.comp_node();
  37. info->ptr = Tensor::make(data);
  38. m_valid_handle.insert(info);
  39. return info;
  40. }
  41. void ChannelImpl::del(void* handle) {
  42. mgb_assert(m_valid_handle.erase(handle), "invalid handle: %p", handle);
  43. m_worker.add_task(Del{reinterpret_cast<TensorInfo*>(handle)});
  44. }
  45. void ChannelImpl::swap_in(void* handle) {
  46. if (m_enable_evict & SWAP) {
  47. mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
  48. "invalid handle: %p", handle);
  49. m_worker.add_task(SwapIn{reinterpret_cast<TensorInfo*>(handle)});
  50. }
  51. }
  52. void ChannelImpl::swap_out(void* handle) {
  53. if (m_enable_evict & SWAP) {
  54. mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
  55. "invalid handle: %p", handle);
  56. m_worker.add_task(SwapOut{reinterpret_cast<TensorInfo*>(handle)});
  57. }
  58. }
  59. void ChannelImpl::drop(void* handle) {
  60. if (m_enable_evict & DROP) {
  61. mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
  62. "invalid handle: %p", handle);
  63. m_worker.add_task(Drop{reinterpret_cast<TensorInfo*>(handle)});
  64. }
  65. }
  66. SmallVector<void*> ChannelImpl::apply_op(
  67. std::shared_ptr<OpDef> op,
  68. const SmallVector<void*>& inputs) {
  69. for (auto i : inputs) {
  70. mgb_assert(m_valid_handle.find(i) != m_valid_handle.end(),
  71. "invalid handle: %p", i);
  72. }
  73. SmallVector<TensorInfo*> input_infos;
  74. input_infos.reserve(inputs.size());
  75. SmallVector<LogicalTensorDesc> input_descs;
  76. input_descs.reserve(inputs.size());
  77. std::unique_lock<decltype(m_mutex)> lock(m_mutex);
  78. for (auto i : inputs) {
  79. auto info = reinterpret_cast<TensorInfo*>(i);
  80. mgb_assert(!info->invalid, "Invalid tensor, unable to apply_op!");
  81. input_infos.push_back(info);
  82. input_descs.push_back(info->desc);
  83. }
  84. lock.unlock();
  85. auto [output_descs, validated] = OpDef::infer_output_attrs_fallible(*op, input_descs);
  86. ApplyOp cmd{std::move(op)};
  87. cmd.inputs = std::move(input_infos);
  88. cmd.outputs.reserve(output_descs.size());
  89. SmallVector<void*> outputs;
  90. // FIXME: remove this check when op check is correct
  91. bool validated_bkp = true;
  92. for (size_t i = 0;i < output_descs.size();i ++) {
  93. auto&& desc = output_descs[i];
  94. if (desc.layout.ndim == 0) {
  95. validated_bkp = false;
  96. }
  97. auto info = alloc();
  98. info->desc = desc;
  99. m_valid_handle.insert(info);
  100. cmd.outputs.push_back(info);
  101. outputs.push_back(info);
  102. }
  103. if (m_enable_evict & DROP) {
  104. for (auto out : cmd.outputs) {
  105. out->path.op = cmd.op;
  106. for (auto out_ : cmd.outputs) {
  107. out->path.outputs.push_back(m_st.at(out_));
  108. }
  109. for (auto inp : cmd.inputs) {
  110. out->path.inputs.push_back(m_st.at(inp));
  111. inp->path.dep_outputs.push_back(m_st.at(out));
  112. }
  113. }
  114. }
  115. m_worker.add_task(std::move(cmd));
  116. if (!(validated && validated_bkp) && m_async_level == 1) {
  117. sync();
  118. } else if (m_async_level == 0) {
  119. sync();
  120. // check device error
  121. for (auto&& oup : outputs) {
  122. auto info = reinterpret_cast<TensorInfo*>(oup);
  123. info->ptr->comp_node().sync();
  124. }
  125. }
  126. return outputs;
  127. }
  128. HostTensorND ChannelImpl::get_value(void* handle) {
  129. mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
  130. "invalid handle: %p", handle);
  131. auto info = reinterpret_cast<TensorInfo*>(handle);
  132. std::unique_lock<decltype(m_mutex)> lock(m_mutex);
  133. mgb_assert(!m_waitee);
  134. if (!info->value_fetched) {
  135. mgb_assert(!info->invalid, "Invalid tensor, unable to get_value!");
  136. m_waitee = info;
  137. m_worker.add_task(GetValue{info});
  138. m_cv.wait(lock, [&]() {
  139. check_worker_exc_unsafe();
  140. return info->value_fetched;
  141. });
  142. m_waitee = nullptr;
  143. }
  144. mgb_assert(info->ptr->value_fetched());
  145. return info->ptr->get_value();
  146. }
  147. TensorShape ChannelImpl::get_shape(void* handle) {
  148. mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
  149. "invalid handle: %p", handle);
  150. auto info = reinterpret_cast<TensorInfo*>(handle);
  151. if (info->desc.layout.ndim != 0) {
  152. return info->desc.layout;
  153. }
  154. std::unique_lock<decltype(m_mutex)> lock(m_mutex);
  155. mgb_assert(!m_waitee);
  156. m_waitee = info;
  157. m_cv.wait(lock, [&]() {
  158. check_worker_exc_unsafe();
  159. return bool(info->ptr);
  160. });
  161. m_waitee = nullptr;
  162. TensorShape ret = info->ptr->layout();
  163. mgb_assert(ret.ndim != 0);
  164. return ret;
  165. }
  166. DType ChannelImpl::get_dtype(void* handle) {
  167. mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
  168. "invalid handle: %p", handle);
  169. auto info = reinterpret_cast<TensorInfo*>(handle);
  170. auto ret = info->desc.layout.dtype;
  171. mgb_assert(ret.valid());
  172. return ret;
  173. }
  174. CompNode ChannelImpl::get_device(void* handle) {
  175. mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
  176. "invalid handle: %p", handle);
  177. auto info = reinterpret_cast<TensorInfo*>(handle);
  178. auto ret = info->desc.comp_node;
  179. mgb_assert(ret.valid());
  180. return ret;
  181. }
  182. DeviceTensorND ChannelImpl::get_dev_tensor(void* handle) {
  183. mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
  184. "invalid handle: %p", handle);
  185. auto info = reinterpret_cast<TensorInfo*>(handle);
  186. std::unique_lock<decltype(m_mutex)> lock(m_mutex);
  187. mgb_assert(!m_waitee);
  188. m_waitee = info;
  189. m_cv.wait(lock, [&]() {
  190. check_worker_exc_unsafe();
  191. return bool(info->ptr);
  192. });
  193. m_waitee = nullptr;
  194. return info->ptr->dev_tensor();
  195. }
  196. void ChannelImpl::sync() {
  197. m_worker.wait_all_task_finish();
  198. MGB_LOCK_GUARD(m_mutex);
  199. check_worker_exc_unsafe();
  200. }
  201. void ChannelImpl::close() {
  202. sync();
  203. }
  204. void ChannelImpl::config_async_level(int level) {
  205. mgb_assert(level <= 2 and level >= 0, "async_level should be 0, 1 or 2");
  206. m_async_level = level;
  207. }
  208. int ChannelImpl::get_async_level() {
  209. return m_async_level;
  210. }
  211. TensorInfo* ChannelImpl::alloc() {
  212. MGB_LOCK_GUARD(m_mutex);
  213. auto info = m_pool.alloc();
  214. m_st.insert(info);
  215. return info;
  216. }
  217. void ChannelImpl::free(TensorInfo* ptr) {
  218. MGB_LOCK_GUARD(m_mutex);
  219. if (ptr->path.dep_outputs.size() > 0) {
  220. remove_dep(ptr);
  221. }
  222. m_st.erase(ptr);
  223. mgb_assert(ptr->allow_delete, "delete before ref_cnt = 0");
  224. m_pool.free(ptr);
  225. }
  226. ChannelImpl::~ChannelImpl() {
  227. close();
  228. }
  229. void ChannelImpl::produce_tensor(TensorInfo* dest, TensorPtr ptr, bool notice = true) {
  230. if (notice) {
  231. MGB_LOCK_GUARD(m_mutex);
  232. dest->value_fetched = ptr->value_fetched();
  233. // update tensor desc for static infer
  234. // if (dest->desc.layout.ndim) {
  235. // mgb_assert(dest->desc.layout.eq_shape(ptr->layout()));
  236. // }
  237. dest->desc.layout = ptr->layout();
  238. dest->desc.comp_node = ptr->comp_node();
  239. dest->ptr = std::move(ptr);
  240. if (m_waitee == dest) {
  241. m_cv.notify_all();
  242. }
  243. } else {
  244. dest->value_fetched = ptr->value_fetched();
  245. // update tensor desc for static infer
  246. dest->desc.layout = ptr->layout();
  247. dest->desc.comp_node = ptr->comp_node();
  248. dest->ptr = std::move(ptr);
  249. }
  250. }
  251. void ChannelImpl::do_swap_out(TensorInfo* dest) {
  252. if (dest->evict_type == DROP) {
  253. mgb_log_warn("the evict type of tensor %p was set to DROP, this SWAP operation will be ignored", dest);
  254. return;
  255. }
  256. if (!dest->ptr) {
  257. return;
  258. }
  259. dest->evict_type = SWAP;
  260. dest->value_fetched = false;
  261. // TODO: swap in parallel
  262. dest->h_value.copy_from(dest->ptr->dev_tensor()).sync();
  263. dest->ptr.reset();
  264. }
  265. void ChannelImpl::do_swap_in(TensorInfo* dest) {
  266. if (dest->ptr) {
  267. return;
  268. }
  269. if (dest->h_value.empty()) {
  270. mgb_log_error("backup of the tensor %p not found", dest);
  271. return;
  272. }
  273. produce_tensor(dest, Tensor::make(dest->h_value), false);
  274. dest->evict_type = NONE;
  275. }
  276. void ChannelImpl::remove_dep(TensorInfo* dest) {
  277. for (auto i : dest->path.dep_outputs) {
  278. auto out_ptr = i.lock();
  279. if (out_ptr) {
  280. regenerate(out_ptr.get(), true);
  281. }
  282. }
  283. }
  284. void ChannelImpl::do_drop(TensorInfo* dest) {
  285. if (dest->evict_type == SWAP) {
  286. mgb_log_warn("the evict type of tensor %p was set to SWAP, this DROP operation will be ignored", dest);
  287. return;
  288. }
  289. if (!dest->path.op) {
  290. mgb_log_warn("the input that produced tensor %p has been deleted, this drop operation will be ignored", dest);
  291. return;
  292. }
  293. if (dest->recompute_times >= m_max_recompute_time) {
  294. mgb_log_warn("the recomputation time for tensor %p exceeds the limit, this drop operation will be ignored", dest);
  295. return;
  296. }
  297. if (!dest->ptr) {
  298. return;
  299. }
  300. dest->evict_type = DROP;
  301. dest->value_fetched = false;
  302. dest->ptr.reset();
  303. }
  304. void ChannelImpl::set_swap_flag(bool flag) {
  305. if (flag) {
  306. m_enable_evict |= SWAP;
  307. } else {
  308. m_enable_evict &= ~SWAP;
  309. }
  310. }
  311. void ChannelImpl::set_drop_flag(bool flag) {
  312. if (flag) {
  313. m_enable_evict |= DROP;
  314. } else {
  315. m_enable_evict &= ~DROP;
  316. }
  317. }
  318. void ChannelImpl::regenerate(TensorInfo* info, bool must_drop = false) {
  319. if (!info->ptr && info->evict_type != NONE) {
  320. if (info->evict_type == SWAP) {
  321. do_swap_in(info);
  322. } else {
  323. mgb_assert(info->evict_type == DROP);
  324. mgb_assert(info->path.op, "recomputation path not found");
  325. auto path = info->path;
  326. SmallVector<TensorPtr> inputs;
  327. inputs.reserve(path.inputs.size());
  328. for (auto i : path.inputs) {
  329. mgb_assert(i, "invalid history input");
  330. if (!i->ptr) {
  331. regenerate(i.get(), must_drop);
  332. }
  333. inputs.push_back(i->ptr);
  334. }
  335. auto outputs = OpDef::apply_on_physical_tensor(*path.op, inputs);
  336. for (size_t i = 0; i < outputs.size(); i ++) {
  337. auto out_ptr = path.outputs[i].lock();
  338. if (out_ptr) {
  339. out_ptr->recompute_times ++;
  340. if (!out_ptr->ptr && out_ptr->evict_type == DROP) {
  341. produce_tensor(out_ptr.get(), std::move(outputs[i]), false);
  342. }
  343. }
  344. }
  345. }
  346. }
  347. if (must_drop) {
  348. if (info->path.op) {
  349. info->path.op.reset();
  350. info->path.inputs.clear();
  351. if (info->evict_type == DROP) {
  352. info->evict_type = NONE;
  353. }
  354. }
  355. }
  356. }
  357. void ChannelImpl::process_one_task(Command& cmd) {
  358. //TODO: remove std::visit for support osx 10.12
  359. std::visit([this](auto& cmd) {
  360. using T = std::remove_reference_t<decltype(cmd)>;
  361. try {
  362. if constexpr (std::is_same_v<T, Put>) {
  363. produce_tensor(cmd.dest, Tensor::make(cmd.value));
  364. } else if constexpr (std::is_same_v<T, ApplyOp>) {
  365. SmallVector<TensorPtr> tensor_inputs;
  366. tensor_inputs.reserve(cmd.inputs.size());
  367. for (auto i : cmd.inputs) {
  368. if (m_enable_evict && i->evict_type != NONE) {
  369. if (!i->ptr) {
  370. regenerate(i);
  371. }
  372. }
  373. mgb_assert(i->ptr, "Invalid input tensor ptr!");
  374. tensor_inputs.push_back(i->ptr);
  375. }
  376. auto tensor_outputs = OpDef::apply_on_physical_tensor(*cmd.op, tensor_inputs);
  377. mgb_assert(tensor_outputs.size() == cmd.outputs.size());
  378. for (size_t i = 0; i < tensor_outputs.size(); ++i) {
  379. produce_tensor(cmd.outputs[i], std::move(tensor_outputs[i]));
  380. }
  381. } else if constexpr (std::is_same_v<T, Del>) {
  382. free(cmd.dest);
  383. } else if constexpr (std::is_same_v<T, GetValue>) {
  384. if (m_enable_evict && cmd.dest->evict_type != NONE) {
  385. if (!cmd.dest->ptr) {
  386. regenerate(cmd.dest);
  387. }
  388. }
  389. mgb_assert(cmd.dest->ptr, "Invalid tensor ptr!");
  390. cmd.dest->ptr->fetch_value();
  391. MGB_LOCK_GUARD(m_mutex);
  392. cmd.dest->value_fetched = true;
  393. if (m_waitee == cmd.dest) {
  394. m_cv.notify_all();
  395. }
  396. } else if constexpr (std::is_same_v<T, SwapIn>) {
  397. do_swap_in(cmd.dest);
  398. } else if constexpr (std::is_same_v<T, SwapOut>) {
  399. do_swap_out(cmd.dest);
  400. } else if constexpr (std::is_same_v<T, Drop>) {
  401. do_drop(cmd.dest);
  402. } else {
  403. static_assert(!std::is_same_v<T, T>);
  404. }
  405. } catch (...) {
  406. MGB_LOCK_GUARD(m_mutex);
  407. if constexpr (std::is_same_v<T, ApplyOp>) {
  408. for (auto oup : cmd.outputs) {
  409. oup->invalid = true;
  410. }
  411. } else if constexpr (std::is_same_v<T, Put>) {
  412. cmd.dest->invalid = true;
  413. }
  414. m_worker_exc = std::current_exception();
  415. m_cv.notify_all();
  416. }
  417. }, cmd);
  418. }
  419. void ChannelImpl::check_worker_exc_unsafe() {
  420. if (m_worker_exc) {
  421. std::exception_ptr exc;
  422. std::swap(exc, m_worker_exc);
  423. std::rethrow_exception(exc);
  424. }
  425. }

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台