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

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