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.h 12 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. /**
  2. * \file imperative/src/impl/interpreter/interpreter_impl.h
  3. * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  4. *
  5. * Copyright (c) 2014-2021 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. #pragma once
  12. #include <deque>
  13. #include <future>
  14. #include <list>
  15. #include <stack>
  16. #include <thread>
  17. #include <unordered_set>
  18. #include <variant>
  19. #include "megbrain/comp_node.h"
  20. #include "megbrain/utils/mempool.h"
  21. #include "megbrain/imperative/interpreter.h"
  22. #include "megbrain/imperative/profiler.h"
  23. #include "./commands.h"
  24. #include "./tensor_info.h"
  25. #include "./option_manager.h"
  26. #include "./stack_manager.h"
  27. #include "../profiler/events.h"
  28. namespace mgb::imperative::interpreter::intl {
  29. using Handle = Interpreter::Handle;
  30. struct InterpreterImpl : Interpreter {
  31. std::unique_ptr<Channel> create_channel() override;
  32. };
  33. struct ChannelImpl : Interpreter::Channel {
  34. ChannelImpl();
  35. ~ChannelImpl() override;
  36. Handle put(const HostTensorND& value, bool no_cache) override;
  37. Handle put(const DeviceTensorND& value, const HostTensorND& hvalue) override;
  38. void del(Handle) override;
  39. void swap_in(Handle) override;
  40. void swap_out(Handle) override;
  41. void drop(Handle) override;
  42. SmallVector<Handle> apply_op(
  43. std::shared_ptr<OpDef> op,
  44. const SmallVector<Handle>& inputs) override;
  45. HostTensorND get_value(Handle) override;
  46. TensorShape get_shape(Handle) override;
  47. DType get_dtype(Handle) override;
  48. CompNode get_device(Handle) override;
  49. DeviceTensorND get_dev_tensor(Handle) override;
  50. bool check_available() override;
  51. void sync() override;
  52. void close() override;
  53. size_t get_option(std::string name) override;
  54. void set_option(std::string name, size_t value) override;
  55. void start_profile() override;
  56. void stop_profile() override;
  57. void push_scope(std::string) override;
  58. void pop_scope(std::string) override;
  59. private:
  60. struct WorkQueue;
  61. struct State;
  62. TensorInfo* alloc();
  63. void init(TensorInfo*, LogicalTensorDesc desc);
  64. void free(TensorInfo*);
  65. void real_free(TensorInfo*);
  66. void recursive_free(TensorInfo*);
  67. void do_drop(TensorInfo*, bool);
  68. void detach_users(TensorInfo*);
  69. TensorInfo* put_impl(const HostTensorND& value, bool no_cache);
  70. TensorInfo* put_impl(const DeviceTensorND& value, const HostTensorND& hvalue);
  71. void del_impl(Handle);
  72. void sync_impl();
  73. SmallVector<Handle> apply_op_impl(
  74. std::shared_ptr<OpDef> op,
  75. const SmallVector<Handle>& inputs);
  76. TensorPtr wait_tensor(TensorInfo* info, profiler::TensorProp prop);
  77. void notify_tensor_unsafe(TensorInfo* info);
  78. void process_one_task(Command&);
  79. void check_worker_exc_unsafe();
  80. void produce_tensor(TensorInfo* dest, TensorPtr ptr);
  81. void release_tensor(TensorInfo* dest);
  82. void regenerate(TensorInfo* dest);
  83. void do_apply_op(const ApplyOp& cmd);
  84. void flush_apply_stack();
  85. std::tuple<SmallVector<MemoryDesc>, SmallVector<TensorPtr>, SmallVector<TensorPtr>> init_output_and_workspace(
  86. const OpDef& def,
  87. SmallVector<TensorPtr> inputs,
  88. SmallVector<MemoryDesc> inputs_mem_desc);
  89. void dispatch_default_cpu(
  90. std::shared_ptr<OpDef> op,
  91. const SmallVector<TensorInfo*>& input_infos,
  92. const SmallVector<LogicalTensorDesc>& input_descs,
  93. SmallVector<Handle>* outputs);
  94. void dispatch_kernel(
  95. std::shared_ptr<OpDef> op,
  96. const SmallVector<TensorInfo*>& input_infos,
  97. const SmallVector<LogicalTensorDesc>& input_descs,
  98. SmallVector<Handle>* outputs);
  99. void push_scope(std::string, State&);
  100. void pop_scope(std::string, State&);
  101. void assert_in_channel();
  102. void assert_in_worker();
  103. std::thread::id get_worker_tid();
  104. // template <typename TCommand>
  105. // void enqueue_command(TCommand&& cmd) {
  106. // m_buffer.enqueue(Command{std::forward<TCommand>(cmd)});
  107. // }
  108. void sample_on_device(CompNode device, bool force);
  109. // valid => status != Deleted
  110. std::unordered_set<TensorInfo*> collect_valid_tensors();
  111. std::mutex m_mutex;
  112. Spinlock m_spin;
  113. std::condition_variable m_cv;
  114. MemPool<TensorInfo> m_pool;
  115. std::unordered_set<Handle> m_valid_handle;
  116. TensorInfo* m_waitee = nullptr;
  117. uint64_t m_waitee_id = 0;
  118. std::exception_ptr m_worker_exc;
  119. std::function<void(std::string, std::string)> m_profile_dump_callback;
  120. size_t m_storage_id = 0;
  121. std::stack<std::tuple<ApplyOp, size_t, TensorInfo*>> m_apply_stack;
  122. bool m_applying = false;
  123. bool m_closed = false;
  124. struct WorkQueue : AsyncQueueSC<Command, WorkQueue> {
  125. // set max_spin=0 to prevent Queue fetch task in busy wait manner.
  126. // this won't affect throughput when python interpreter is sending enough task,
  127. // but will significantly save CPU time when waiting for task, e.g. wait for data input
  128. // limit pending tasks to 10000
  129. WorkQueue(ChannelImpl* owner)
  130. : AsyncQueueSC<Command, WorkQueue>(0, 10000), m_owner(owner) {
  131. sys::set_thread_name("interpreter");
  132. if (const char* env_val = MGB_GETENV("MEGENGINE_ASYNC_QUEUE_SIZE")) {
  133. int len = strlen(env_val);
  134. for (int i = 0; i < len; i ++) {
  135. mgb_assert(env_val[i] >= '0' && env_val[i] <= '9', "async queue size should be an integer");
  136. }
  137. size_t val;
  138. sscanf(env_val, "%zu", &val);
  139. update_max_items(val);
  140. }
  141. }
  142. void process_one_task(Command& icmd) {
  143. m_owner->process_one_task(icmd);
  144. }
  145. void on_async_queue_worker_thread_start() override;
  146. private:
  147. ChannelImpl* m_owner;
  148. } m_worker;
  149. /**
  150. * Buf a command window for following fuse
  151. * example:
  152. * ---------------------------------------------------------------------
  153. * | ..., Apply{in: (i0, i1), out: (o0, o1)}, ... + Del{i0} + Del{i1} |
  154. * ---------------------------------------------------------------------
  155. * | ..., Apply{in: (i0, i1), out: (o0, o1), del: (i0)}, ... + Del{i1} |
  156. * ---------------------------------------------------------------------
  157. * | ..., Apply{in: (i0, i1), out: (o0, o1), del: (i0, i1)}, ... |
  158. * ---------------------------------------------------------------------
  159. * Then the fused Apply may be invoked inplace. see: ChannelImpl::process_one_task
  160. */
  161. struct CommandBuffer {
  162. CommandBuffer(ChannelImpl* owner) : m_owner(owner) {}
  163. void enqueue(CommandData cmd);
  164. bool empty() const {
  165. return m_commands.empty();
  166. }
  167. void flush();
  168. private:
  169. ChannelImpl* m_owner;
  170. std::deque<Command> m_commands;
  171. using Handle = decltype(m_commands)::iterator;
  172. // [begin, end)
  173. using Range = std::array<Handle, 2>;
  174. // Launch commands in range [m_commands.begin(), pos)
  175. void flush(Handle pos);
  176. // Select flush position for incoming cmd
  177. Handle flush_pos_for(const Command& cmd);
  178. // Fuse del command into suitable ApplyOp
  179. bool fuse_del(const Del& cmd);
  180. // Returns the last handle that dest is used within range. If dest is not used, returns range[1]
  181. Handle find_last_usage(TensorInfo* dest, Range range);
  182. // Returns the produce position of dest. If not found, returns range[1]
  183. Handle find_produce(TensorInfo* dest, Range range);
  184. } m_buffer;
  185. //! config whether raise error exactly when invoking op.
  186. //! level 2: both device and user side errors are async;
  187. //! level 1: user side errors are sync;
  188. //! level 0: both sync.
  189. int m_async_level = 2;
  190. struct State {
  191. std::thread::id tid;
  192. OptionManager options;
  193. };
  194. struct ChannelState: State {
  195. StackManager stack_manager;
  196. };
  197. struct WorkerState: State {};
  198. ChannelState m_channel_state;
  199. WorkerState m_worker_state;
  200. /*!
  201. * \brief A framework of dynamic sublienar memory optimization
  202. *
  203. * Note: The main idea is that during the training process, if the memory
  204. * usage exceeds the threshold, select some tensors to evict until the
  205. * memory usage is below the threshold.
  206. */
  207. struct DynamicSublinear {
  208. /*!
  209. * \brief find an available tensor with the largest evaluation function
  210. *
  211. * Note: An available tensor must satisfy: (1) has computing path,
  212. * (2) is in memory, (3) is not pinned. Evaluation function refers to:
  213. * @see: TensorInfo::eval_func.
  214. *
  215. * \return the pointer of the best tensor; nullptr is returned if no
  216. * available tensor is found
  217. */
  218. TensorInfo* find_best_tensor(bool);
  219. /*!
  220. * \brief estimate the cost of recomputing tensor ptr
  221. *
  222. * Note: We define the cost as the sum of the costs of each evicted
  223. * components where all the neighbors of ptr are located.
  224. */
  225. double estimate_neighbor_cost(TensorInfo* ptr);
  226. /*!
  227. * \brief update the last used time of the tensor ptr
  228. */
  229. void update_used_time(TensorInfo* ptr);
  230. /*!
  231. * \brief merge the two specified sets (the set in which the element x
  232. * is located, and the set in which the element y is located)
  233. */
  234. void merge(std::shared_ptr<DsuNode> &x, std::shared_ptr<DsuNode> &y);
  235. /*!
  236. * \brief return the representative of the set that contains the
  237. * element x
  238. */
  239. std::shared_ptr<DsuNode> find_father(std::shared_ptr<DsuNode> &x);
  240. /*!
  241. * \brief update DSU after recomputing tensor ptr
  242. *
  243. * Delete ptr from the set where ptr is located. Since DSU does not
  244. * support this operation, instead, we reset the DSU father of ptr, and
  245. * subtract the recomputation cost of ptr from the cost of the original
  246. * set.
  247. */
  248. void update_dsu_after_recompute(TensorInfo* ptr);
  249. /*!
  250. * \brief update DSU after evicting tensor ptr
  251. *
  252. * Check the neighbors of x, that is, the input and output tensors, and
  253. * if they are evicted, merge their respective sets.
  254. */
  255. void update_dsu_after_evict(TensorInfo* ptr);
  256. /*!
  257. * \brief pin the tensors in vec
  258. */
  259. void pin(const SmallVector<TensorInfo*>& vec);
  260. /*!
  261. * \brief unpin the tensors in vec
  262. */
  263. void unpin(const SmallVector<TensorInfo*>& vec);
  264. /*!
  265. * \brief add the tensor to the candidate set
  266. *
  267. * If the size of the tensor does not exceed the minimum threshold,
  268. * it will do nothing.
  269. */
  270. void insert_candidate(TensorInfo* ptr);
  271. /*!
  272. * \brief erase the tensor from the candidate set
  273. *
  274. * If the size of the tensor does not exceed the minimum threshold,
  275. * it will do nothing.
  276. */
  277. void erase_candidate(TensorInfo* ptr);
  278. //! estimate the current time, in order to reduce the overhead of timer
  279. double estimate_timestamp = 0;
  280. //! the comp node where dynamic sublinear memory optimization works
  281. CompNode comp_node;
  282. //! store all tensors that may be evicted
  283. std::unordered_set<TensorInfo*> candidates;
  284. bool is_bad_op(std::string op_name) {
  285. return std::find(op_blacklist.begin(), op_blacklist.end(), op_name) != op_blacklist.end();
  286. }
  287. std::vector<std::string> op_blacklist = {"CollectiveComm", "InplaceAdd",
  288. "ParamPackSplit", "ParamPackConcat", "GaussianRNG", "UniformRNG",
  289. "GammaRNG", "PermutationRNG", "PoissonRNG", "BetaRNG"};
  290. } m_dtr;
  291. //! automatically evict an optimal tensor
  292. bool auto_evict(size_t);
  293. void alloc_tensor_with_evict(Blob*);
  294. // assert thread id when call get_xxx_state to avoid misuse
  295. ChannelState& get_channel_state();
  296. WorkerState& get_worker_state();
  297. };
  298. } // namespace mgb::imperative::interpreter::intl

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