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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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_standard_layout<T>::value, "invalid type");
  153. result.append(reinterpret_cast<const char*>(&val), sizeof(T));
  154. }
  155. static void serialize_write_pod(const char* val, std::string& result) {
  156. result.append(val, strlen(val));
  157. }
  158. template <typename T>
  159. static T deserialize_read_pod(const std::string& data, size_t offset = 0) {
  160. static_assert(std::is_standard_layout<T>::value, "invalid type");
  161. T ret;
  162. //! A pointer to an object or incomplete type may be converted to a
  163. //! pointer to a different object or incomplete type. If the resulting
  164. //! pointer is not correctly aligned for the pointed-to type, the
  165. //! behavior is undefined.
  166. //!
  167. //! so here we should use memcpy instead of
  168. //! *reinterpret_cast<const T*>(&data[offset]);
  169. memcpy(&ret, data.data() + offset, sizeof(T));
  170. return ret;
  171. }
  172. template <typename T>
  173. static T deserialize_read_pod(const char* data, size_t offset = 0) {
  174. static_assert(std::is_standard_layout<T>::value, "invalid type");
  175. T ret;
  176. //! A pointer to an object or incomplete type may be converted to a
  177. //! pointer to a different object or incomplete type. If the resulting
  178. //! pointer is not correctly aligned for the pointed-to type, the
  179. //! behavior is undefined.
  180. //!
  181. //! so here we should use memcpy instead of
  182. //! *reinterpret_cast<const T*>(&data[offset]);
  183. memcpy(&ret, data + offset, sizeof(T));
  184. return ret;
  185. }
  186. enum class OprType : uint32_t {
  187. MATRIX_MUL_FORWARD,
  188. BATCHED_MATRIX_MUL_FORWARD,
  189. CONVOLUTION_FORWARD,
  190. CONVOLUTION_BACKWARD_DATA,
  191. CONVOLUTION_BACKWARD_FILTER,
  192. CONVOLUTION3D_FORWARD,
  193. CONVOLUTION3D_BACKWARD_DATA,
  194. CONVOLUTION3D_BACKWARD_FILTER,
  195. LOCAL_SHARE_FORWARD,
  196. LOCAL_SHARE_BACKWARD_DATA,
  197. LOCAL_SHARE_BACKWARD_FILTER,
  198. DEFORMABLE_CONV_FORWARD,
  199. DEFORMABLE_CONV_BACKWARD_DATA,
  200. DEFORMABLE_CONV_BACKWARD_FILTER,
  201. CONVBIAS_FORWARD,
  202. BATCH_CONV_FORWARD,
  203. };
  204. struct SearchItem {
  205. OprType opr_type;
  206. //! serialized param
  207. std::string param;
  208. TensorLayoutArray layouts;
  209. };
  210. /**
  211. * \brief get subopr list of the algo
  212. *
  213. * \param layouts origin layouts of the parent opr
  214. * \param opr parent opr
  215. */
  216. virtual std::vector<SearchItem> get_subopr_list(const TensorLayoutArray&,
  217. const OperatorBase*) const {
  218. return {};
  219. }
  220. protected:
  221. Handle::HandleType m_handle_type = Handle::HandleType::NAIVE;
  222. };
  223. MEGDNN_DEF_ENUM_CLASS_BIT_OPR(Algorithm::Attribute)
  224. //! policy for executing the operator
  225. struct ExecutionPolicy {
  226. //! INVALID_ALGO_TYPE algo_type means using heuristic
  227. Algorithm::Info::Desc algo;
  228. std::vector<ExecutionPolicy> sub_policy;
  229. };
  230. /*!
  231. * \brief define Algorithm and ExecutionPolicy for oprs that have
  232. * multiple impl algos
  233. *
  234. * \tparam Opr the operator class
  235. * \tparam nargs number of arguments
  236. */
  237. template <class Opr, int nargs>
  238. class MultiAlgoOpr;
  239. //! base def
  240. template <class Opr>
  241. class MultiAlgoOpr<Opr, -1> {
  242. public:
  243. using AlgorithmInfo = detail::Algorithm::Info;
  244. using AlgorithmDesc = detail::Algorithm::Info::Desc;
  245. using Algorithm = detail::Algorithm;
  246. /*!
  247. * \brief get a string representation for current algorithm set;
  248. *
  249. * get_all_algorithms() may return different algorithms only if
  250. * algorithm set name differs. This is used for checking cache
  251. * validity.
  252. */
  253. virtual const char* get_algorithm_set_name() const = 0;
  254. ExecutionPolicy& execution_policy() { return m_execution_policy; }
  255. const ExecutionPolicy& execution_policy() const {
  256. return m_execution_policy;
  257. }
  258. virtual Algorithm* get_algorithm_from_desc(const AlgorithmDesc&) = 0;
  259. protected:
  260. ~MultiAlgoOpr() = default;
  261. private:
  262. ExecutionPolicy m_execution_policy;
  263. };
  264. //! specialize for nargs == 3
  265. template <class Opr>
  266. class MultiAlgoOpr<Opr, 3> : public MultiAlgoOpr<Opr, -1> {
  267. public:
  268. using Algorithm = detail::Algorithm;
  269. using AlgorithmInfo = detail::Algorithm::Info;
  270. //! get all possible algorithm decriptions for the specified layouts
  271. std::vector<AlgorithmInfo> get_all_algorithms_info(const TensorLayout& p0,
  272. const TensorLayout& p1,
  273. const TensorLayout& p2) {
  274. std::vector<AlgorithmInfo> ret;
  275. for (auto&& algo : get_all_algorithms(p0, p1, p2)) {
  276. ret.emplace_back(algo->info());
  277. }
  278. return ret;
  279. }
  280. /**
  281. * \brief Returns the best algorithm information which indicate the
  282. * algorithm by heuristic.
  283. *
  284. * The selected algorithm should not use workspace more than
  285. * \p workspace_limit_in_bytes.
  286. */
  287. AlgorithmInfo get_algorithm_info_heuristic(
  288. const TensorLayout& p0, const TensorLayout& p1,
  289. const TensorLayout& p2,
  290. size_t workspace_limit_in_bytes =
  291. std::numeric_limits<size_t>::max(),
  292. bool reproducible = false) {
  293. return get_algorithm_heuristic(p0, p1, p2, workspace_limit_in_bytes,
  294. reproducible)
  295. ->info();
  296. }
  297. protected:
  298. ~MultiAlgoOpr() = default;
  299. //! get all possible algorithms for the specified layouts
  300. virtual std::vector<Algorithm*> get_all_algorithms(
  301. const TensorLayout& p0, const TensorLayout& p1,
  302. const TensorLayout& p2) = 0;
  303. /**
  304. * \brief Returns the best algorithm by heuristic.
  305. *
  306. * The selected algorithm should not use workspace more than
  307. * \p workspace_limit_in_bytes.
  308. */
  309. virtual Algorithm* get_algorithm_heuristic(
  310. const TensorLayout& p0, const TensorLayout& p1,
  311. const TensorLayout& p2,
  312. size_t workspace_limit_in_bytes =
  313. std::numeric_limits<size_t>::max(),
  314. bool reproducible = false) = 0;
  315. };
  316. //! specializae for nargs == 4
  317. template <class Opr>
  318. class MultiAlgoOpr<Opr, 4> : public MultiAlgoOpr<Opr, -1> {
  319. public:
  320. using Algorithm = detail::Algorithm;
  321. using AlgorithmInfo = detail::Algorithm::Info;
  322. //! get all possible algorithm decriptions for the specified layouts
  323. std::vector<AlgorithmInfo> get_all_algorithms_info(const TensorLayout& p0,
  324. const TensorLayout& p1,
  325. const TensorLayout& p2,
  326. const TensorLayout& p3) {
  327. std::vector<AlgorithmInfo> ret;
  328. for (auto&& algo : get_all_algorithms(p0, p1, p2, p3)) {
  329. ret.emplace_back(algo->info());
  330. }
  331. return ret;
  332. }
  333. /**
  334. * \brief Returns the best algorithm information which indicate the
  335. * algorithm by heuristic.
  336. *
  337. * The selected algorithm should not use workspace more than
  338. * \p workspace_limit_in_bytes.
  339. */
  340. AlgorithmInfo get_algorithm_info_heuristic(
  341. const TensorLayout& p0, const TensorLayout& p1,
  342. const TensorLayout& p2, const TensorLayout& p3,
  343. size_t workspace_limit_in_bytes =
  344. std::numeric_limits<size_t>::max(),
  345. bool reproducible = false) {
  346. return get_algorithm_heuristic(p0, p1, p2, p3, workspace_limit_in_bytes,
  347. reproducible)
  348. ->info();
  349. }
  350. protected:
  351. ~MultiAlgoOpr() = default;
  352. //! get all possible algorithms for the specified layouts
  353. virtual std::vector<Algorithm*> get_all_algorithms(
  354. const TensorLayout& p0, const TensorLayout& p1,
  355. const TensorLayout& p2, const TensorLayout& p3) = 0;
  356. /**
  357. * \brief Returns the best algorithm by heuristic.
  358. *
  359. * The selected algorithm should not use workspace more than
  360. * \p workspace_limit_in_bytes.
  361. */
  362. virtual Algorithm* get_algorithm_heuristic(
  363. const TensorLayout& p0, const TensorLayout& p1,
  364. const TensorLayout& p2, const TensorLayout& p3,
  365. size_t workspace_limit_in_bytes =
  366. std::numeric_limits<size_t>::max(),
  367. bool reproducible = false) = 0;
  368. };
  369. //! specializae for nargs == 5
  370. template <class Opr>
  371. class MultiAlgoOpr<Opr, 5> : public MultiAlgoOpr<Opr, -1> {
  372. public:
  373. using Algorithm = detail::Algorithm;
  374. using AlgorithmInfo = detail::Algorithm::Info;
  375. //! get all possible algorithm decriptions for the specified layouts
  376. std::vector<AlgorithmInfo> get_all_algorithms_info(const TensorLayout& p0,
  377. const TensorLayout& p1,
  378. const TensorLayout& p2,
  379. const TensorLayout& p3,
  380. const TensorLayout& p4) {
  381. std::vector<AlgorithmInfo> ret;
  382. for (auto&& algo : get_all_algorithms(p0, p1, p2, p3, p4)) {
  383. ret.emplace_back(algo->info());
  384. }
  385. return ret;
  386. }
  387. /**
  388. * \brief Returns the best algorithm information which indicate the
  389. * algorithm by heuristic.
  390. *
  391. * The selected algorithm should not use workspace more than
  392. * \p workspace_limit_in_bytes.
  393. */
  394. AlgorithmInfo get_algorithm_info_heuristic(
  395. const TensorLayout& p0, const TensorLayout& p1,
  396. const TensorLayout& p2, const TensorLayout& p3,
  397. const TensorLayout& p4,
  398. size_t workspace_limit_in_bytes =
  399. std::numeric_limits<size_t>::max(),
  400. bool reproducible = false) {
  401. return get_algorithm_heuristic(p0, p1, p2, p3, p4,
  402. workspace_limit_in_bytes, reproducible)
  403. ->info();
  404. }
  405. protected:
  406. ~MultiAlgoOpr() = default;
  407. //! get all possible algorithms for the specified layouts
  408. virtual std::vector<Algorithm*> get_all_algorithms(
  409. const TensorLayout& p0, const TensorLayout& p1,
  410. const TensorLayout& p2, const TensorLayout& p3,
  411. const TensorLayout& p4) = 0;
  412. /**
  413. * \brief Returns the best algorithm by heuristic.
  414. *
  415. * The selected algorithm should not use workspace more than
  416. * \p workspace_limit_in_bytes.
  417. */
  418. virtual Algorithm* get_algorithm_heuristic(
  419. const TensorLayout& p0, const TensorLayout& p1,
  420. const TensorLayout& p2, const TensorLayout& p3,
  421. const TensorLayout& p4,
  422. size_t workspace_limit_in_bytes =
  423. std::numeric_limits<size_t>::max(),
  424. bool reproducible = false) = 0;
  425. };
  426. //! specializae for nargs == 8
  427. template <class Opr>
  428. class MultiAlgoOpr<Opr, 8> : public MultiAlgoOpr<Opr, -1> {
  429. public:
  430. using Algorithm = detail::Algorithm;
  431. using AlgorithmInfo = detail::Algorithm::Info;
  432. //! get all possible algorithm decriptions for the specified layouts
  433. std::vector<AlgorithmInfo> get_all_algorithms_info(
  434. const TensorLayout& p0, const TensorLayout& p1,
  435. const TensorLayout& p2, const TensorLayout& p3,
  436. const TensorLayout& p4, const TensorLayout& p5,
  437. const TensorLayout& p6, const TensorLayout& p7) {
  438. std::vector<AlgorithmInfo> ret;
  439. for (auto&& algo : get_all_algorithms(p0, p1, p2, p3, p4, p5, p6, p7)) {
  440. ret.emplace_back(algo->info());
  441. }
  442. return ret;
  443. }
  444. /**
  445. * \brief Returns the best algorithm information which indicate the
  446. * algorithm by heuristic.
  447. *
  448. * The selected algorithm should not use workspace more than
  449. */
  450. AlgorithmInfo get_algorithm_info_heuristic(
  451. const TensorLayout& p0, const TensorLayout& p1,
  452. const TensorLayout& p2, const TensorLayout& p3,
  453. const TensorLayout& p4, const TensorLayout& p5,
  454. const TensorLayout& p6, const TensorLayout& p7,
  455. size_t workspace_limit_in_bytes =
  456. std::numeric_limits<size_t>::max(),
  457. bool reproducible = false) {
  458. return get_algorithm_heuristic(p0, p1, p2, p3, p4, p5, p6, p7,
  459. workspace_limit_in_bytes, reproducible)
  460. ->info();
  461. }
  462. protected:
  463. ~MultiAlgoOpr() = default;
  464. //! get all possible algorithms for the specified layouts
  465. virtual std::vector<Algorithm*> get_all_algorithms(
  466. const TensorLayout& p0, const TensorLayout& p1,
  467. const TensorLayout& p2, const TensorLayout& p3,
  468. const TensorLayout& p4, const TensorLayout& p5,
  469. const TensorLayout& p6, const TensorLayout& p7) = 0;
  470. /**
  471. * \brief Returns the best algorithm by heuristic.
  472. *
  473. * The selected algorithm should not use workspace more than
  474. * \p workspace_limit_in_bytes.
  475. */
  476. virtual Algorithm* get_algorithm_heuristic(
  477. const TensorLayout& p0, const TensorLayout& p1,
  478. const TensorLayout& p2, const TensorLayout& p3,
  479. const TensorLayout& p4, const TensorLayout& p5,
  480. const TensorLayout& p6, const TensorLayout& p7,
  481. size_t workspace_limit_in_bytes =
  482. std::numeric_limits<size_t>::max(),
  483. bool reproducible = false) = 0;
  484. };
  485. } // namespace detail
  486. using Algorithm = detail::Algorithm;
  487. using AlgoAttribute = Algorithm::Attribute;
  488. using ExecutionPolicy = detail::ExecutionPolicy;
  489. } // namespace megdnn
  490. #include "megdnn/internal/visibility_epilogue.h"
  491. // vim: syntax=cpp.doxygen

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