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.

base.h 19 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. /**
  2. * \file dnn/include/megdnn/oprs/base.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
  10. * implied.
  11. */
  12. #pragma once
  13. #include <type_traits>
  14. #include "megdnn/basic_types.h"
  15. #include "megdnn/handle.h"
  16. #include "megdnn/internal/visibility_prologue.h"
  17. namespace megdnn {
  18. class Handle;
  19. /**
  20. * \brief base class for all operators
  21. *
  22. * This is an helper class. Users should not use OperatorBase directly.
  23. * Operators should be created by handle->create_opr<>().
  24. *
  25. * Each operator must provides the following constexpr values:
  26. *
  27. * * NR_INPUTS: number of input vars
  28. * * NR_OUTPUTS: number of output vars
  29. * * OPERATOR_TYPE: operator type as an enum
  30. *
  31. * If the operator has dynamic inputs or in_out param, the corresponding
  32. * NR_INPUTS is -1.
  33. *
  34. * For an operator whose NR_INPUTS >= 0 and NR_OUTPUTS >= 0, the operator must
  35. * also provide following methods:
  36. *
  37. * * void exec(_megdnn_in inputs..., _megdnn_tensor_out outputs...,
  38. * _megdnn_workspace workspace)
  39. * * void deduce_layout(const TensorLayout& inputs...,
  40. * TensorLayout& outputs...)
  41. * * size_t get_workspace_in_bytes(const TensorLayout &inputs...,
  42. * const TensorLayout &outputs)
  43. */
  44. class OperatorBase {
  45. public:
  46. explicit OperatorBase(Handle* handle) : m_handle(handle) {}
  47. virtual ~OperatorBase();
  48. //! get the handle from which this operator is created
  49. Handle* handle() const { return m_handle; }
  50. //! whether this opr guarantees that its exec() is thread-safe
  51. virtual bool is_thread_safe() const { return false; }
  52. /*!
  53. * \brief set the tracker to be used with MegcoreAsyncErrorInfo
  54. *
  55. * Most operators do not have async errors so this function has a
  56. * default empty implementation.
  57. */
  58. virtual void set_error_tracker(void*) {}
  59. private:
  60. Handle* m_handle;
  61. };
  62. namespace detail {
  63. /**
  64. * \brief AlgoSelectionStrategy is the advance information for selecting
  65. * algo
  66. */
  67. enum class AlgoSelectionStrategy {
  68. HEURISTIC = 0, //!< heristic to select the algos
  69. FAST_RUN = 1,
  70. FULL_RUN = 2,
  71. };
  72. /**
  73. * \brief separate algo by datatype for Matmul and conv
  74. */
  75. enum class AlgoDataType : uint32_t {
  76. FLOAT32 = 1 << 0,
  77. FLOAT16 = 1 << 1,
  78. QINT8X8X32 = 1 << 2,
  79. QUINT8X8X32 = 1 << 3,
  80. INT8X8X16 = 1 << 4,
  81. INT16X16X32 = 1 << 5,
  82. INT4X4X16 = 1 << 6,
  83. };
  84. /*!
  85. * \brief Abstract representation of an algorithm for implementing
  86. * the operator
  87. */
  88. class Algorithm {
  89. public:
  90. static constexpr uint32_t INVALID_ALGO_TYPE = static_cast<uint32_t>(-1);
  91. /**
  92. * \brief the attribe of the algo, such as REPRODUCIBLE, NAIVE
  93. *
  94. */
  95. enum class Attribute : uint32_t {
  96. /**
  97. * \brief whether the execution result is
  98. * reproducible across multiple runs.
  99. */
  100. REPRODUCIBLE = 1 << 0,
  101. /**
  102. * \brief whether the algo is naive
  103. * Mark algorithms with simple implementation as NAIVE, so we can filter
  104. * these algorithms to speed up fastrun.
  105. * */
  106. NAIVE = 1 << 1,
  107. };
  108. /**
  109. * \brief Algorithm information, we can get real algo from
  110. * AlgorithmInfo::Info::Desc
  111. */
  112. struct Info {
  113. struct Desc {
  114. //! backend of the algo belonging to
  115. Handle::HandleType handle_type;
  116. //! indicate the real algo implementation
  117. uint32_t type = INVALID_ALGO_TYPE;
  118. //! serialized param of the algo type
  119. std::string param;
  120. bool valid() const { return type != INVALID_ALGO_TYPE; }
  121. void reset() { type = INVALID_ALGO_TYPE; }
  122. bool operator==(const Desc& rhs) const {
  123. return handle_type == rhs.handle_type && type == rhs.type &&
  124. param == rhs.param;
  125. }
  126. } desc;
  127. //! algorithm name
  128. std::string name;
  129. Attribute attribute;
  130. bool valid() const { return desc.valid(); }
  131. void reset() { desc.reset(); }
  132. //! desc donate the algo
  133. bool operator==(const Info& rhs) const { return desc == rhs.desc; }
  134. };
  135. virtual ~Algorithm() = default;
  136. /**
  137. * \brief get the attribute of the algo
  138. */
  139. virtual Attribute attribute() const = 0;
  140. virtual const char* name() const = 0;
  141. //! serialized param
  142. virtual std::string param() const { return {}; }
  143. virtual uint32_t type() const = 0;
  144. bool contain_attribute(const Attribute& attr) const;
  145. Handle::HandleType handle_type() const { return m_handle_type; }
  146. Info info() const {
  147. return {{handle_type(), type(), param()}, name(), attribute()};
  148. }
  149. Info::Desc desc() const { return {handle_type(), type(), param()}; }
  150. template <typename T>
  151. static void serialize_write_pod(const T& val, std::string& result) {
  152. static_assert(std::is_trivially_copyable<T>::value,
  153. "type should be trivially copyable");
  154. static_assert(!std::is_pointer<T>::value,
  155. "serialize pointer is unsafe in eager execution mode");
  156. result.append(reinterpret_cast<const char*>(&val), sizeof(T));
  157. }
  158. static void serialize_write_pod(const char* val, std::string& result) {
  159. result.append(val, strlen(val));
  160. }
  161. template <typename T>
  162. static T deserialize_read_pod(const std::string& data, size_t offset = 0) {
  163. static_assert(std::is_trivially_copyable<T>::value, "invalid type");
  164. T ret;
  165. //! A pointer to an object or incomplete type may be converted to a
  166. //! pointer to a different object or incomplete type. If the resulting
  167. //! pointer is not correctly aligned for the pointed-to type, the
  168. //! behavior is undefined.
  169. //!
  170. //! so here we should use memcpy instead of
  171. //! *reinterpret_cast<const T*>(&data[offset]);
  172. memcpy(&ret, data.data() + offset, sizeof(T));
  173. return ret;
  174. }
  175. template <typename T>
  176. static T deserialize_read_pod(const char* data, size_t offset = 0) {
  177. static_assert(std::is_trivially_copyable<T>::value, "invalid type");
  178. T ret;
  179. //! A pointer to an object or incomplete type may be converted to a
  180. //! pointer to a different object or incomplete type. If the resulting
  181. //! pointer is not correctly aligned for the pointed-to type, the
  182. //! behavior is undefined.
  183. //!
  184. //! so here we should use memcpy instead of
  185. //! *reinterpret_cast<const T*>(&data[offset]);
  186. memcpy(&ret, data + offset, sizeof(T));
  187. return ret;
  188. }
  189. enum class OprType : uint32_t {
  190. MATRIX_MUL_FORWARD,
  191. BATCHED_MATRIX_MUL_FORWARD,
  192. CONVOLUTION_FORWARD,
  193. CONVOLUTION_BACKWARD_DATA,
  194. CONVOLUTION_BACKWARD_FILTER,
  195. CONVOLUTION3D_FORWARD,
  196. CONVOLUTION3D_BACKWARD_DATA,
  197. CONVOLUTION3D_BACKWARD_FILTER,
  198. LOCAL_SHARE_FORWARD,
  199. LOCAL_SHARE_BACKWARD_DATA,
  200. LOCAL_SHARE_BACKWARD_FILTER,
  201. DEFORMABLE_CONV_FORWARD,
  202. DEFORMABLE_CONV_BACKWARD_DATA,
  203. DEFORMABLE_CONV_BACKWARD_FILTER,
  204. CONVBIAS_FORWARD,
  205. BATCH_CONV_FORWARD,
  206. };
  207. struct SearchItem {
  208. OprType opr_type;
  209. //! serialized param
  210. std::string param;
  211. TensorLayoutArray layouts;
  212. };
  213. /**
  214. * \brief get subopr list of the algo
  215. *
  216. * \param layouts origin layouts of the parent opr
  217. * \param opr parent opr
  218. */
  219. virtual std::vector<SearchItem> get_subopr_list(const TensorLayoutArray&,
  220. const OperatorBase*) const {
  221. return {};
  222. }
  223. protected:
  224. Handle::HandleType m_handle_type = Handle::HandleType::NAIVE;
  225. };
  226. MEGDNN_DEF_ENUM_CLASS_BIT_OPR(Algorithm::Attribute)
  227. //! policy for executing the operator
  228. struct ExecutionPolicy {
  229. //! INVALID_ALGO_TYPE algo_type means using heuristic
  230. Algorithm::Info::Desc algo;
  231. std::vector<ExecutionPolicy> sub_policy;
  232. };
  233. /*!
  234. * \brief define Algorithm and ExecutionPolicy for oprs that have
  235. * multiple impl algos
  236. *
  237. * \tparam Opr the operator class
  238. * \tparam nargs number of arguments
  239. */
  240. template <class Opr, int nargs>
  241. class MultiAlgoOpr;
  242. //! base def
  243. template <class Opr>
  244. class MultiAlgoOpr<Opr, -1> {
  245. public:
  246. using AlgorithmInfo = detail::Algorithm::Info;
  247. using AlgorithmDesc = detail::Algorithm::Info::Desc;
  248. using Algorithm = detail::Algorithm;
  249. /*!
  250. * \brief get a string representation for current algorithm set;
  251. *
  252. * get_all_algorithms() may return different algorithms only if
  253. * algorithm set name differs. This is used for checking cache
  254. * validity.
  255. */
  256. virtual const char* get_algorithm_set_name() const = 0;
  257. ExecutionPolicy& execution_policy() { return m_execution_policy; }
  258. const ExecutionPolicy& execution_policy() const {
  259. return m_execution_policy;
  260. }
  261. virtual Algorithm* get_algorithm_from_desc(const AlgorithmDesc&) = 0;
  262. protected:
  263. ~MultiAlgoOpr() = default;
  264. private:
  265. ExecutionPolicy m_execution_policy;
  266. };
  267. //! specialize for nargs == 3
  268. template <class Opr>
  269. class MultiAlgoOpr<Opr, 3> : public MultiAlgoOpr<Opr, -1> {
  270. public:
  271. using Algorithm = detail::Algorithm;
  272. using AlgorithmInfo = detail::Algorithm::Info;
  273. //! get all possible algorithm decriptions for the specified layouts
  274. std::vector<AlgorithmInfo> get_all_algorithms_info(const TensorLayout& p0,
  275. const TensorLayout& p1,
  276. const TensorLayout& p2) {
  277. std::vector<AlgorithmInfo> ret;
  278. for (auto&& algo : get_all_algorithms(p0, p1, p2)) {
  279. ret.emplace_back(algo->info());
  280. }
  281. return ret;
  282. }
  283. /**
  284. * \brief Returns the best algorithm information which indicate the
  285. * algorithm by heuristic.
  286. *
  287. * The selected algorithm should not use workspace more than
  288. * \p workspace_limit_in_bytes.
  289. */
  290. AlgorithmInfo get_algorithm_info_heuristic(
  291. const TensorLayout& p0, const TensorLayout& p1,
  292. const TensorLayout& p2,
  293. size_t workspace_limit_in_bytes =
  294. std::numeric_limits<size_t>::max(),
  295. bool reproducible = false) {
  296. return get_algorithm_heuristic(p0, p1, p2, workspace_limit_in_bytes,
  297. reproducible)
  298. ->info();
  299. }
  300. protected:
  301. ~MultiAlgoOpr() = default;
  302. //! get all possible algorithms for the specified layouts
  303. virtual std::vector<Algorithm*> get_all_algorithms(
  304. const TensorLayout& p0, const TensorLayout& p1,
  305. const TensorLayout& p2) = 0;
  306. /**
  307. * \brief Returns the best algorithm by heuristic.
  308. *
  309. * The selected algorithm should not use workspace more than
  310. * \p workspace_limit_in_bytes.
  311. */
  312. virtual Algorithm* get_algorithm_heuristic(
  313. const TensorLayout& p0, const TensorLayout& p1,
  314. const TensorLayout& p2,
  315. size_t workspace_limit_in_bytes =
  316. std::numeric_limits<size_t>::max(),
  317. bool reproducible = false) = 0;
  318. };
  319. //! specializae for nargs == 4
  320. template <class Opr>
  321. class MultiAlgoOpr<Opr, 4> : public MultiAlgoOpr<Opr, -1> {
  322. public:
  323. using Algorithm = detail::Algorithm;
  324. using AlgorithmInfo = detail::Algorithm::Info;
  325. //! get all possible algorithm decriptions for the specified layouts
  326. std::vector<AlgorithmInfo> get_all_algorithms_info(const TensorLayout& p0,
  327. const TensorLayout& p1,
  328. const TensorLayout& p2,
  329. const TensorLayout& p3) {
  330. std::vector<AlgorithmInfo> ret;
  331. for (auto&& algo : get_all_algorithms(p0, p1, p2, p3)) {
  332. ret.emplace_back(algo->info());
  333. }
  334. return ret;
  335. }
  336. /**
  337. * \brief Returns the best algorithm information which indicate the
  338. * algorithm by heuristic.
  339. *
  340. * The selected algorithm should not use workspace more than
  341. * \p workspace_limit_in_bytes.
  342. */
  343. AlgorithmInfo get_algorithm_info_heuristic(
  344. const TensorLayout& p0, const TensorLayout& p1,
  345. const TensorLayout& p2, const TensorLayout& p3,
  346. size_t workspace_limit_in_bytes =
  347. std::numeric_limits<size_t>::max(),
  348. bool reproducible = false) {
  349. return get_algorithm_heuristic(p0, p1, p2, p3, workspace_limit_in_bytes,
  350. reproducible)
  351. ->info();
  352. }
  353. protected:
  354. ~MultiAlgoOpr() = default;
  355. //! get all possible algorithms for the specified layouts
  356. virtual std::vector<Algorithm*> get_all_algorithms(
  357. const TensorLayout& p0, const TensorLayout& p1,
  358. const TensorLayout& p2, const TensorLayout& p3) = 0;
  359. /**
  360. * \brief Returns the best algorithm by heuristic.
  361. *
  362. * The selected algorithm should not use workspace more than
  363. * \p workspace_limit_in_bytes.
  364. */
  365. virtual Algorithm* get_algorithm_heuristic(
  366. const TensorLayout& p0, const TensorLayout& p1,
  367. const TensorLayout& p2, const TensorLayout& p3,
  368. size_t workspace_limit_in_bytes =
  369. std::numeric_limits<size_t>::max(),
  370. bool reproducible = false) = 0;
  371. };
  372. //! specializae for nargs == 5
  373. template <class Opr>
  374. class MultiAlgoOpr<Opr, 5> : public MultiAlgoOpr<Opr, -1> {
  375. public:
  376. using Algorithm = detail::Algorithm;
  377. using AlgorithmInfo = detail::Algorithm::Info;
  378. //! get all possible algorithm decriptions for the specified layouts
  379. std::vector<AlgorithmInfo> get_all_algorithms_info(const TensorLayout& p0,
  380. const TensorLayout& p1,
  381. const TensorLayout& p2,
  382. const TensorLayout& p3,
  383. const TensorLayout& p4) {
  384. std::vector<AlgorithmInfo> ret;
  385. for (auto&& algo : get_all_algorithms(p0, p1, p2, p3, p4)) {
  386. ret.emplace_back(algo->info());
  387. }
  388. return ret;
  389. }
  390. /**
  391. * \brief Returns the best algorithm information which indicate the
  392. * algorithm by heuristic.
  393. *
  394. * The selected algorithm should not use workspace more than
  395. * \p workspace_limit_in_bytes.
  396. */
  397. AlgorithmInfo get_algorithm_info_heuristic(
  398. const TensorLayout& p0, const TensorLayout& p1,
  399. const TensorLayout& p2, const TensorLayout& p3,
  400. const TensorLayout& p4,
  401. size_t workspace_limit_in_bytes =
  402. std::numeric_limits<size_t>::max(),
  403. bool reproducible = false) {
  404. return get_algorithm_heuristic(p0, p1, p2, p3, p4,
  405. workspace_limit_in_bytes, reproducible)
  406. ->info();
  407. }
  408. protected:
  409. ~MultiAlgoOpr() = default;
  410. //! get all possible algorithms for the specified layouts
  411. virtual std::vector<Algorithm*> get_all_algorithms(
  412. const TensorLayout& p0, const TensorLayout& p1,
  413. const TensorLayout& p2, const TensorLayout& p3,
  414. const TensorLayout& p4) = 0;
  415. /**
  416. * \brief Returns the best algorithm by heuristic.
  417. *
  418. * The selected algorithm should not use workspace more than
  419. * \p workspace_limit_in_bytes.
  420. */
  421. virtual Algorithm* get_algorithm_heuristic(
  422. const TensorLayout& p0, const TensorLayout& p1,
  423. const TensorLayout& p2, const TensorLayout& p3,
  424. const TensorLayout& p4,
  425. size_t workspace_limit_in_bytes =
  426. std::numeric_limits<size_t>::max(),
  427. bool reproducible = false) = 0;
  428. };
  429. //! specializae for nargs == 8
  430. template <class Opr>
  431. class MultiAlgoOpr<Opr, 8> : public MultiAlgoOpr<Opr, -1> {
  432. public:
  433. using Algorithm = detail::Algorithm;
  434. using AlgorithmInfo = detail::Algorithm::Info;
  435. //! get all possible algorithm decriptions for the specified layouts
  436. std::vector<AlgorithmInfo> get_all_algorithms_info(
  437. const TensorLayout& p0, const TensorLayout& p1,
  438. const TensorLayout& p2, const TensorLayout& p3,
  439. const TensorLayout& p4, const TensorLayout& p5,
  440. const TensorLayout& p6, const TensorLayout& p7) {
  441. std::vector<AlgorithmInfo> ret;
  442. for (auto&& algo : get_all_algorithms(p0, p1, p2, p3, p4, p5, p6, p7)) {
  443. ret.emplace_back(algo->info());
  444. }
  445. return ret;
  446. }
  447. /**
  448. * \brief Returns the best algorithm information which indicate the
  449. * algorithm by heuristic.
  450. *
  451. * The selected algorithm should not use workspace more than
  452. */
  453. AlgorithmInfo get_algorithm_info_heuristic(
  454. const TensorLayout& p0, const TensorLayout& p1,
  455. const TensorLayout& p2, const TensorLayout& p3,
  456. const TensorLayout& p4, const TensorLayout& p5,
  457. const TensorLayout& p6, const TensorLayout& p7,
  458. size_t workspace_limit_in_bytes =
  459. std::numeric_limits<size_t>::max(),
  460. bool reproducible = false) {
  461. return get_algorithm_heuristic(p0, p1, p2, p3, p4, p5, p6, p7,
  462. workspace_limit_in_bytes, reproducible)
  463. ->info();
  464. }
  465. protected:
  466. ~MultiAlgoOpr() = default;
  467. //! get all possible algorithms for the specified layouts
  468. virtual std::vector<Algorithm*> get_all_algorithms(
  469. const TensorLayout& p0, const TensorLayout& p1,
  470. const TensorLayout& p2, const TensorLayout& p3,
  471. const TensorLayout& p4, const TensorLayout& p5,
  472. const TensorLayout& p6, const TensorLayout& p7) = 0;
  473. /**
  474. * \brief Returns the best algorithm by heuristic.
  475. *
  476. * The selected algorithm should not use workspace more than
  477. * \p workspace_limit_in_bytes.
  478. */
  479. virtual Algorithm* get_algorithm_heuristic(
  480. const TensorLayout& p0, const TensorLayout& p1,
  481. const TensorLayout& p2, const TensorLayout& p3,
  482. const TensorLayout& p4, const TensorLayout& p5,
  483. const TensorLayout& p6, const TensorLayout& p7,
  484. size_t workspace_limit_in_bytes =
  485. std::numeric_limits<size_t>::max(),
  486. bool reproducible = false) = 0;
  487. };
  488. } // namespace detail
  489. using Algorithm = detail::Algorithm;
  490. using AlgoAttribute = Algorithm::Attribute;
  491. using ExecutionPolicy = detail::ExecutionPolicy;
  492. } // namespace megdnn
  493. #include "megdnn/internal/visibility_epilogue.h"
  494. // vim: syntax=cpp.doxygen

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