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 21 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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. #include "megbrain/imperative/opr_utility.h"
  14. #include "megbrain/imperative/ops/backward_graph.h"
  15. #include "megbrain/imperative/ops/autogen.h"
  16. using namespace mgb;
  17. using namespace imperative;
  18. using namespace interpreter;
  19. using namespace interpreter::intl;
  20. std::unique_ptr<Interpreter::Channel> InterpreterImpl::create_channel() {
  21. return std::make_unique<ChannelImpl>();
  22. }
  23. Interpreter& Interpreter::inst() {
  24. static InterpreterImpl inst_;
  25. return inst_;
  26. }
  27. void* ChannelImpl::put(const HostTensorND& value, bool no_cache) {
  28. auto info = alloc();
  29. info->desc.layout = value.layout();
  30. info->desc.comp_node = value.comp_node();
  31. info->desc.value = value.proxy_to_default_cpu();
  32. m_valid_handle.insert(info);
  33. m_buffer.enqueue(Put{info, value, no_cache});
  34. return info;
  35. }
  36. void* ChannelImpl::put(const DeviceTensorND& data) {
  37. auto info = alloc();
  38. info->desc.layout = data.layout();
  39. info->desc.comp_node = data.comp_node();
  40. info->ptr = Tensor::make(data);
  41. m_valid_handle.insert(info);
  42. return info;
  43. }
  44. void ChannelImpl::del(void* handle) {
  45. mgb_assert(m_valid_handle.erase(handle), "invalid handle: %p", handle);
  46. m_buffer.enqueue(Del{reinterpret_cast<TensorInfo*>(handle)});
  47. }
  48. void ChannelImpl::swap_in(void* handle) {
  49. if (m_enable_evict & SWAP) {
  50. mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
  51. "invalid handle: %p", handle);
  52. m_buffer.enqueue(SwapIn{reinterpret_cast<TensorInfo*>(handle)});
  53. }
  54. }
  55. void ChannelImpl::swap_out(void* handle) {
  56. if (m_enable_evict & SWAP) {
  57. mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
  58. "invalid handle: %p", handle);
  59. m_buffer.enqueue(SwapOut{reinterpret_cast<TensorInfo*>(handle)});
  60. }
  61. }
  62. void ChannelImpl::drop(void* handle) {
  63. if (m_enable_evict & DROP) {
  64. mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
  65. "invalid handle: %p", handle);
  66. m_buffer.enqueue(Drop{reinterpret_cast<TensorInfo*>(handle)});
  67. }
  68. }
  69. SmallVector<void*> ChannelImpl::apply_op(
  70. std::shared_ptr<OpDef> op,
  71. const SmallVector<void*>& inputs) {
  72. for (auto i : inputs) {
  73. mgb_assert(m_valid_handle.find(i) != m_valid_handle.end(),
  74. "invalid handle: %p", i);
  75. }
  76. SmallVector<TensorInfo*> input_infos;
  77. input_infos.reserve(inputs.size());
  78. SmallVector<LogicalTensorDesc> input_descs;
  79. input_descs.reserve(inputs.size());
  80. {
  81. MGB_LOCK_GUARD(m_mutex);
  82. for (auto i : inputs) {
  83. auto info = reinterpret_cast<TensorInfo*>(i);
  84. mgb_assert(!info->invalid, "Invalid tensor, unable to apply_op!");
  85. input_infos.push_back(info);
  86. input_descs.push_back(info->desc);
  87. }
  88. }
  89. auto [output_descs, validated] = OpDef::infer_output_attrs_fallible(*op, input_descs);
  90. ApplyOp cmd{std::move(op)};
  91. cmd.inputs = std::move(input_infos);
  92. cmd.outputs.reserve(output_descs.size());
  93. SmallVector<void*> outputs;
  94. // FIXME: remove this check when op check is correct
  95. bool validated_bkp = true;
  96. for (size_t i = 0;i < output_descs.size();i ++) {
  97. auto&& desc = output_descs[i];
  98. if (desc.layout.ndim == 0) {
  99. validated_bkp = false;
  100. }
  101. auto info = alloc();
  102. info->desc = desc;
  103. m_valid_handle.insert(info);
  104. cmd.outputs.push_back(info);
  105. outputs.push_back(info);
  106. }
  107. if (m_enable_evict & DROP) {
  108. for (auto out : cmd.outputs) {
  109. out->path.op = cmd.op;
  110. for (auto out_ : cmd.outputs) {
  111. out->path.outputs.push_back(m_st.at(out_));
  112. }
  113. for (auto inp : cmd.inputs) {
  114. out->path.inputs.push_back(m_st.at(inp));
  115. inp->path.dep_outputs.push_back(m_st.at(out));
  116. }
  117. }
  118. }
  119. m_buffer.enqueue(std::move(cmd));
  120. if (!(validated && validated_bkp) && m_async_level == 1) {
  121. sync();
  122. } else if (m_async_level == 0) {
  123. sync();
  124. // check device error
  125. for (auto&& oup : outputs) {
  126. auto info = reinterpret_cast<TensorInfo*>(oup);
  127. info->ptr->comp_node().sync();
  128. }
  129. }
  130. return outputs;
  131. }
  132. HostTensorND ChannelImpl::get_value(void* handle) {
  133. mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
  134. "invalid handle: %p", handle);
  135. auto info = reinterpret_cast<TensorInfo*>(handle);
  136. std::unique_lock<decltype(m_mutex)> lock(m_mutex);
  137. mgb_assert(!m_waitee);
  138. if (!info->value_fetched) {
  139. mgb_assert(!info->invalid, "Invalid tensor, unable to get_value!");
  140. m_waitee = info;
  141. m_buffer.enqueue(GetValue{info});
  142. m_cv.wait(lock, [&]() {
  143. check_worker_exc_unsafe();
  144. return info->value_fetched;
  145. });
  146. m_waitee = nullptr;
  147. }
  148. mgb_assert(info->ptr->value_fetched());
  149. return info->ptr->get_value();
  150. }
  151. TensorShape ChannelImpl::get_shape(void* handle) {
  152. mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
  153. "invalid handle: %p", handle);
  154. auto info = reinterpret_cast<TensorInfo*>(handle);
  155. if (info->desc.layout.ndim != 0) {
  156. return info->desc.layout;
  157. }
  158. std::unique_lock<decltype(m_mutex)> lock(m_mutex);
  159. mgb_assert(!m_waitee);
  160. m_waitee = info;
  161. m_buffer.enqueue(Flush{info});
  162. m_cv.wait(lock, [&]() {
  163. check_worker_exc_unsafe();
  164. return static_cast<bool>(info->ptr);
  165. });
  166. m_waitee = nullptr;
  167. TensorShape ret = info->ptr->layout();
  168. mgb_assert(ret.ndim != 0);
  169. return ret;
  170. }
  171. DType ChannelImpl::get_dtype(void* handle) {
  172. mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
  173. "invalid handle: %p", handle);
  174. auto info = reinterpret_cast<TensorInfo*>(handle);
  175. auto ret = info->desc.layout.dtype;
  176. mgb_assert(ret.valid());
  177. return ret;
  178. }
  179. CompNode ChannelImpl::get_device(void* handle) {
  180. mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
  181. "invalid handle: %p", handle);
  182. auto info = reinterpret_cast<TensorInfo*>(handle);
  183. auto ret = info->desc.comp_node;
  184. mgb_assert(ret.valid());
  185. return ret;
  186. }
  187. DeviceTensorND ChannelImpl::get_dev_tensor(void* handle) {
  188. mgb_assert(m_valid_handle.find(handle) != m_valid_handle.end(),
  189. "invalid handle: %p", handle);
  190. auto info = reinterpret_cast<TensorInfo*>(handle);
  191. std::unique_lock<decltype(m_mutex)> lock(m_mutex);
  192. mgb_assert(!m_waitee);
  193. m_waitee = info;
  194. m_buffer.enqueue(Flush{info});
  195. m_cv.wait(lock, [&]() {
  196. check_worker_exc_unsafe();
  197. return static_cast<bool>(info->ptr);
  198. });
  199. m_waitee = nullptr;
  200. return info->ptr->dev_tensor();
  201. }
  202. void ChannelImpl::sync() {
  203. if (!m_buffer.empty()) {
  204. m_buffer.enqueue(Flush{});
  205. }
  206. m_worker.wait_all_task_finish();
  207. MGB_LOCK_GUARD(m_mutex);
  208. check_worker_exc_unsafe();
  209. }
  210. void ChannelImpl::close() {
  211. sync();
  212. }
  213. void ChannelImpl::config_async_level(int level) {
  214. mgb_assert(level <= 2 && level >= 0, "async_level should be 0, 1 or 2");
  215. m_async_level = level;
  216. }
  217. int ChannelImpl::get_async_level() {
  218. return m_async_level;
  219. }
  220. TensorInfo* ChannelImpl::alloc() {
  221. MGB_LOCK_GUARD(m_mutex);
  222. auto info = m_pool.alloc();
  223. m_st.insert(info);
  224. return info;
  225. }
  226. void ChannelImpl::free(TensorInfo* ptr) {
  227. MGB_LOCK_GUARD(m_mutex);
  228. if (ptr->path.dep_outputs.size() > 0) {
  229. remove_dep(ptr);
  230. }
  231. m_st.erase(ptr);
  232. mgb_assert(ptr->allow_delete, "delete before ref_cnt = 0");
  233. m_pool.free(ptr);
  234. }
  235. ChannelImpl::~ChannelImpl() {
  236. close();
  237. }
  238. void ChannelImpl::produce_tensor(TensorInfo* dest, TensorPtr ptr, bool notice = true) {
  239. if (notice) {
  240. MGB_LOCK_GUARD(m_mutex);
  241. dest->value_fetched = ptr->value_fetched();
  242. // update tensor desc for static infer
  243. // if (dest->desc.layout.ndim) {
  244. // mgb_assert(dest->desc.layout.eq_shape(ptr->layout()));
  245. // }
  246. dest->desc.layout = ptr->layout();
  247. dest->desc.comp_node = ptr->comp_node();
  248. dest->ptr = std::move(ptr);
  249. if (m_waitee == dest) {
  250. m_cv.notify_all();
  251. }
  252. } else {
  253. dest->value_fetched = ptr->value_fetched();
  254. // update tensor desc for static infer
  255. dest->desc.layout = ptr->layout();
  256. dest->desc.comp_node = ptr->comp_node();
  257. dest->ptr = std::move(ptr);
  258. }
  259. }
  260. void ChannelImpl::do_swap_out(TensorInfo* dest) {
  261. if (dest->evict_type == DROP) {
  262. mgb_log_warn("the evict type of tensor %p was set to DROP, this SWAP operation will be ignored", dest);
  263. return;
  264. }
  265. if (!dest->ptr) {
  266. return;
  267. }
  268. dest->evict_type = SWAP;
  269. dest->value_fetched = false;
  270. // TODO: swap in parallel
  271. dest->h_value.copy_from(dest->ptr->dev_tensor()).sync();
  272. dest->ptr.reset();
  273. }
  274. void ChannelImpl::do_swap_in(TensorInfo* dest) {
  275. if (dest->ptr) {
  276. return;
  277. }
  278. if (dest->h_value.empty()) {
  279. mgb_log_error("backup of the tensor %p not found", dest);
  280. return;
  281. }
  282. produce_tensor(dest, Tensor::make(dest->h_value), false);
  283. dest->evict_type = NONE;
  284. }
  285. void ChannelImpl::remove_dep(TensorInfo* dest) {
  286. for (auto i : dest->path.dep_outputs) {
  287. auto out_ptr = i.lock();
  288. if (out_ptr) {
  289. regenerate(out_ptr.get(), true);
  290. }
  291. }
  292. }
  293. void ChannelImpl::do_drop(TensorInfo* dest) {
  294. if (dest->evict_type == SWAP) {
  295. mgb_log_warn("the evict type of tensor %p was set to SWAP, this DROP operation will be ignored", dest);
  296. return;
  297. }
  298. if (!dest->path.op) {
  299. mgb_log_warn("the input that produced tensor %p has been deleted, this drop operation will be ignored", dest);
  300. return;
  301. }
  302. if (dest->recompute_times >= m_max_recompute_time) {
  303. mgb_log_warn("the recomputation time for tensor %p exceeds the limit, this drop operation will be ignored", dest);
  304. return;
  305. }
  306. if (!dest->ptr) {
  307. return;
  308. }
  309. dest->evict_type = DROP;
  310. dest->value_fetched = false;
  311. dest->ptr.reset();
  312. }
  313. void ChannelImpl::set_swap_flag(bool flag) {
  314. if (flag) {
  315. m_enable_evict |= SWAP;
  316. } else {
  317. m_enable_evict &= ~SWAP;
  318. }
  319. }
  320. void ChannelImpl::set_drop_flag(bool flag) {
  321. if (flag) {
  322. m_enable_evict |= DROP;
  323. } else {
  324. m_enable_evict &= ~DROP;
  325. }
  326. }
  327. void ChannelImpl::set_buffer_length(int length) {
  328. m_buffer.set_capacity(length);
  329. }
  330. void ChannelImpl::regenerate(TensorInfo* info, bool must_drop = false) {
  331. if (!info->ptr && info->evict_type != NONE) {
  332. if (info->evict_type == SWAP) {
  333. do_swap_in(info);
  334. } else {
  335. mgb_assert(info->evict_type == DROP);
  336. mgb_assert(info->path.op, "recomputation path not found");
  337. auto path = info->path;
  338. SmallVector<TensorPtr> inputs;
  339. inputs.reserve(path.inputs.size());
  340. for (auto i : path.inputs) {
  341. mgb_assert(i, "invalid history input");
  342. if (!i->ptr) {
  343. regenerate(i.get(), must_drop);
  344. }
  345. inputs.push_back(i->ptr);
  346. }
  347. auto outputs = OpDef::apply_on_physical_tensor(*path.op, inputs);
  348. for (size_t i = 0; i < outputs.size(); i ++) {
  349. auto out_ptr = path.outputs[i].lock();
  350. if (out_ptr) {
  351. out_ptr->recompute_times ++;
  352. if (!out_ptr->ptr && out_ptr->evict_type == DROP) {
  353. produce_tensor(out_ptr.get(), std::move(outputs[i]), false);
  354. }
  355. }
  356. }
  357. }
  358. }
  359. if (must_drop) {
  360. if (info->path.op) {
  361. info->path.op.reset();
  362. info->path.inputs.clear();
  363. if (info->evict_type == DROP) {
  364. info->evict_type = NONE;
  365. }
  366. }
  367. }
  368. }
  369. void ChannelImpl::process_one_task(Command& cmd) {
  370. //TODO: remove std::visit for support osx 10.12
  371. std::visit([this](auto& cmd) {
  372. using T = std::remove_reference_t<decltype(cmd)>;
  373. try {
  374. if constexpr (std::is_same_v<T, Put>) {
  375. auto value = cmd.no_cache ? std::make_shared<Tensor>(cmd.value) : Tensor::make(cmd.value);
  376. produce_tensor(cmd.dest, std::move(value));
  377. } else if constexpr (std::is_same_v<T, ApplyOp>) {
  378. SmallVector<TensorPtr> tensor_inputs;
  379. tensor_inputs.reserve(cmd.inputs.size());
  380. // refcnt == 1, owners: [TensorInfo::ptr]
  381. for (auto i : cmd.inputs) {
  382. if (m_enable_evict && i->evict_type != NONE) {
  383. if (!i->ptr) {
  384. regenerate(i);
  385. }
  386. }
  387. mgb_assert(i->ptr, "Invalid input tensor ptr!");
  388. // refcnt ++, owners: [i->ptr, tensor_inputs]
  389. tensor_inputs.push_back(i->ptr);
  390. }
  391. // Fused by command buffer. @see: CommandBuffer::fuse_del
  392. // Now if dest is inplacable, it's refcnt would be decreased to 1 and owned by tensor_inputs after Del.
  393. // Note for exprs like 'y = x op x', inplace is unsupported yet but Del would be also fused.
  394. for (auto* del : cmd.dels) {
  395. // refcnt --, owners: [tensor_inputs]
  396. // if it's decreased to 1, would be detected at @see: proxy_graph_detail::apply_on_physical_tensor
  397. free(del);
  398. }
  399. // Here std::move is REQUIRED for removing duplicated references.
  400. auto tensor_outputs = OpDef::apply_on_physical_tensor(
  401. *cmd.op, std::move(tensor_inputs));
  402. mgb_assert(tensor_outputs.size() == cmd.outputs.size());
  403. for (size_t i = 0; i < tensor_outputs.size(); ++i) {
  404. produce_tensor(cmd.outputs[i], std::move(tensor_outputs[i]));
  405. }
  406. } else if constexpr (std::is_same_v<T, Del>) {
  407. free(cmd.dest);
  408. } else if constexpr (std::is_same_v<T, GetValue>) {
  409. if (m_enable_evict && cmd.dest->evict_type != NONE) {
  410. if (!cmd.dest->ptr) {
  411. regenerate(cmd.dest);
  412. }
  413. }
  414. mgb_assert(cmd.dest->ptr, "Invalid tensor ptr!");
  415. cmd.dest->ptr->fetch_value();
  416. MGB_LOCK_GUARD(m_mutex);
  417. cmd.dest->value_fetched = true;
  418. if (m_waitee == cmd.dest) {
  419. m_cv.notify_all();
  420. }
  421. } else if constexpr (std::is_same_v<T, SwapIn>) {
  422. do_swap_in(cmd.dest);
  423. } else if constexpr (std::is_same_v<T, SwapOut>) {
  424. do_swap_out(cmd.dest);
  425. } else if constexpr (std::is_same_v<T, Drop>) {
  426. do_drop(cmd.dest);
  427. } else if constexpr (std::is_same_v<T, Move>) {
  428. produce_tensor(cmd.dest, cmd.src->ptr);
  429. free(cmd.src);
  430. } else {
  431. static_assert(std::is_same_v<T, Flush> ||
  432. std::is_same_v<T, Nop>);
  433. }
  434. } catch (...) {
  435. MGB_LOCK_GUARD(m_mutex);
  436. if constexpr (std::is_same_v<T, ApplyOp>) {
  437. for (auto oup : cmd.outputs) {
  438. oup->invalid = true;
  439. }
  440. } else if constexpr (std::is_same_v<T, Put>) {
  441. cmd.dest->invalid = true;
  442. }
  443. m_worker_exc = std::current_exception();
  444. m_cv.notify_all();
  445. }
  446. }, cmd);
  447. }
  448. void ChannelImpl::check_worker_exc_unsafe() {
  449. if (m_worker_exc) {
  450. // for reuse interpreter_for_py after some exception tests
  451. m_waitee = nullptr;
  452. std::exception_ptr exc;
  453. std::swap(exc, m_worker_exc);
  454. std::rethrow_exception(exc);
  455. }
  456. }
  457. void ChannelImpl::CommandBuffer::enqueue(Command cmd) {
  458. if (std::get_if<Del>(&cmd) && fuse_del(std::get<Del>(cmd))) {
  459. return;
  460. }
  461. auto command_repr = std::visit([](auto& cmd){ return cmd.to_string(); }, cmd);
  462. mgb_log_debug("%s Enqueued", command_repr.c_str());
  463. m_commands.push_back(std::move(cmd));
  464. auto flush_pos = flush_pos_for(m_commands.back());
  465. flush(flush_pos);
  466. }
  467. void ChannelImpl::CommandBuffer::flush(Handle pos) {
  468. for (auto iter = m_commands.begin(); iter != pos; ++iter) {
  469. auto command_repr = std::visit([](auto& cmd){ return cmd.to_string(); }, *iter);
  470. mgb_log_debug("%s Flushed", command_repr.c_str());
  471. m_owner->m_worker.add_task(std::move(*iter));
  472. }
  473. m_commands.erase(m_commands.begin(), pos);
  474. }
  475. auto ChannelImpl::CommandBuffer::flush_pos_for(const Command& cmd) -> Handle {
  476. return std::visit([this](const auto& cmd) {
  477. using T = std::decay_t<decltype(cmd)>;
  478. if constexpr (std::is_same_v<T, ApplyOp>) {
  479. auto* op_type = cmd.op->dyn_typeinfo();
  480. if (op_type == RemoteRecv::typeinfo() ||
  481. op_type == RemoteSend::typeinfo() ||
  482. op_type == CollectiveComm::typeinfo() ||
  483. op_type == opr::InputCallback::typeinfo() ||
  484. op_type == opr::OutputCallback::typeinfo() ||
  485. op_type == BackwardGraph::typeinfo()) {
  486. return m_commands.end();
  487. }
  488. } else if constexpr (std::is_same_v<T, GetValue>) {
  489. return m_commands.end();
  490. } else if constexpr (std::is_same_v<T, Flush>) {
  491. if (cmd.dest == nullptr) {
  492. return m_commands.end();
  493. }
  494. auto produce_iter = find_produce(cmd.dest, {m_commands.begin(), m_commands.end()});
  495. if (produce_iter != m_commands.end()) {
  496. return produce_iter + 1;
  497. }
  498. }
  499. if (m_commands.size() > m_capacity) {
  500. return m_commands.begin() + (m_commands.size() - m_capacity);
  501. }
  502. return m_commands.begin();
  503. }, cmd);
  504. }
  505. /**
  506. * 1. Find ApplyOp(dest) in buffered commands
  507. * 2. Check if there are other usages between ApplyOp and Del, return false if not
  508. * 3. Fuse Del into ApplyOp, return true
  509. */
  510. bool ChannelImpl::CommandBuffer::fuse_del(const Del& cmd) {
  511. auto* dest = cmd.dest;
  512. // TODO: eliminate Puts
  513. auto begin = m_commands.begin(), end = m_commands.end();
  514. auto apply_iter = std::find_if(begin, end, [dest](const Command& cmd){
  515. if (auto* apply = std::get_if<ApplyOp>(&cmd)) {
  516. return std::count(apply->inputs.begin(), apply->inputs.end(), dest) > 0;
  517. }
  518. return false;
  519. });
  520. if (apply_iter == end || find_last_usage(dest, {apply_iter+1, end}) != end) {
  521. return false;
  522. }
  523. mgb_log_debug("%s Fused", cmd.to_string().c_str());
  524. std::get<ApplyOp>(*apply_iter).dels.push_back(dest);
  525. return true;
  526. }
  527. auto ChannelImpl::CommandBuffer::find_last_usage(TensorInfo* dest, Range range)
  528. -> Handle {
  529. auto found = range[1];
  530. for (auto iter = range[0]; iter != range[1]; ++iter) {
  531. std::visit([&](const auto& cmd) {
  532. using T = std::decay_t<decltype(cmd)>;
  533. if constexpr (std::is_same_v<T, ApplyOp>) {
  534. if (std::count(cmd.inputs.begin(), cmd.inputs.end(),
  535. dest) > 0) {
  536. found = iter;
  537. }
  538. } else if constexpr (std::is_same_v<T, GetValue>) {
  539. if (cmd.dest == dest) {
  540. found = iter;
  541. }
  542. } else if constexpr (std::is_same_v<T, SwapIn> ||
  543. std::is_same_v<T, SwapOut> ||
  544. std::is_same_v<T, Drop>) {
  545. //TODO: ignore swap-like commands, just remove them from buffer
  546. if (cmd.dest == dest) {
  547. found = iter;
  548. }
  549. }
  550. }, *iter);
  551. };
  552. return found;
  553. }
  554. auto ChannelImpl::CommandBuffer::find_produce(TensorInfo* dest, Range range)
  555. -> Handle {
  556. return std::find_if(range[0], range[1], [dest](auto& cmd) {
  557. return std::visit([dest](const auto& cmd){
  558. using T = std::decay_t<decltype(cmd)>;
  559. if constexpr (std::is_same_v<T, ApplyOp>) {
  560. return std::count(cmd.outputs.begin(), cmd.outputs.end(), dest) > 0;
  561. } else if constexpr (std::is_same_v<T, Put>) {
  562. return cmd.dest == dest;
  563. }
  564. return false;
  565. }, cmd);
  566. });
  567. }

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